Tutorial by Examples

When defining discriminated unions you can name elements of tuple types and use these names during pattern matching. type Shape = | Circle of diameter:int | Rectangle of width:int * height:int let shapeIsTenWide = function | Circle(diameter=10) | Rectangle(width=10) -> t...
Discriminated unions in F# offer a a way to define types which may hold any number of different data types. Their functionality is similar to C++ unions or VB variants, but with the additional benefit of being type safe. // define a discriminated union that can hold either a float or a string type...
Type information does not need to be included in the cases of a discriminated union. By omitting type information you can create a union that simply represents a set of choices, similar to an enum. // This union can represent any one day of the week but none of // them are tied to a specific unde...
Sometimes it's necessary to convert a Discriminated Union to and from a string: module UnionConversion open Microsoft.FSharp.Reflection let toString (x: 'a) = match FSharpValue.GetUnionFields(x, typeof<'a>) with | case, _ -> case.Name let fromStri...
A single case discriminated union is like any other discriminated union except that it only has one case. // Define single-case discriminated union type. type OrderId = OrderId of int // Construct OrderId type. let order = OrderId 123 // Deconstruct using pattern matching. // Parentheses used...
Sometimes it is useful to create union types with only one case to implement record-like types: type Point = Point of float * float let point1 = Point(0.0, 3.0) let point2 = Point(-2.5, -4.0) These become very useful because they can be decomposed via pattern matching in the same way as tu...
With the RequireQualifiedAccess attribute, union cases must be referred to as MyUnion.MyCase instead of just MyCase. This prevents name collisions in the enclosing namespace or module: type [<RequireQualifiedAccess>] Requirements = None | Single | All // Uses the DU with qualified acc...
Recursive type Discriminated unions can be recursive, that is they can refer to themselves in their definition. The prime example here is a tree: type Tree = | Branch of int * Tree list | Leaf of int As an example, let's define the following tree: 1 2 5 3 4 We can defi...

Page 1 of 1