3 people like it.

Refactoring discriminated unions

A simple example that shows how to refactor discriminated unions to extract common members

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
// Given a type 'SomeType' and a discriminated union with
// multiple cases that reference SomeType:

type SomeType = { Name: string }

type Union =
  | Foo of SomeType
  | Bar of SomeType
  | Zoo of int

// We can avoid code duplication when we need to get SomeType
// from the Foo and Bar case by merging them into a single case:

type SomeKind = 
  | Foo | Bar

type Union2 =
  | Some of SomeType
  | Zoo of int
SomeType.Name: string
Multiple items
val string : value:'T -> string

Full name: Microsoft.FSharp.Core.Operators.string

--------------------
type string = System.String

Full name: Microsoft.FSharp.Core.string
type Union =
  | Foo of SomeType
  | Bar of SomeType
  | Zoo of int

Full name: Script.Union
union case Union.Foo: SomeType -> Union
type SomeType =
  {Name: string;}

Full name: Script.SomeType
union case Union.Bar: SomeType -> Union
union case Union.Zoo: int -> Union
Multiple items
val int : value:'T -> int (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.int

--------------------
type int = int32

Full name: Microsoft.FSharp.Core.int

--------------------
type int<'Measure> = int

Full name: Microsoft.FSharp.Core.int<_>
type SomeKind =
  | Foo
  | Bar

Full name: Script.SomeKind
union case SomeKind.Foo: SomeKind
union case SomeKind.Bar: SomeKind
type Union2 =
  | Some of SomeType
  | Zoo of int

Full name: Script.Union2
union case Union2.Some: SomeType -> Union2
union case Union2.Zoo: int -> Union2
Raw view Test code New version

More information

Link:http://fssnip.net/jI
Posted:11 years ago
Author:Tomas Petricek
Tags: discriminated union