Thursday, February 10, 2011

Studying F# : Discriminated Union #3

In phosphorescence: Studying F#: Discriminated Union #2, I mentioned about another similarity between "Discriminated Union" in F# and Java's enum. But there are many different paradigms in there. So I write about two advanced features of "Discriminated Union" in this article.

Discriminated Union can take arguments, differently.


It's the sample from the book "Professional F# 2.0".
type Color =
    | Black
    | Blue
    | Cyan
    | Gray
    | Green
    | Magenta
    | DarkBlue
    | Red
    | White
    | Yellow
    | RGB of int * int * int
    | CMYK of float * float * float * float
Both RGB and CMYK take arguments, and these take different arguments (both arity and type).
> let definedColor = Gray

val definedColor : Color = Gray

> let rgbColor = RGB(128, 128, 128)

val rgbColor : Color = RGB (128,128,128)

> let cmykColor = CMYK(0.0, 0.0, 0.0, 0.5)

val cmykColor : Color = CMYK (0.0,0.0,0.0,0.5)

Define recursively


Discriminated Union can be defined recursively. The simplest sample is "composite pattern"
type Component =
    | Composite of list<Component>
    | Leaf of string

And you can use like below:
> let compositeSample = Composite([ Leaf("foo"); Composite([ Leaf("bar"); Leaf("buzz") ]) ])

val compositeSample : Component =
  Composite [Leaf "foo"; Composite [Leaf "bar"; Leaf "buzz"]]

No comments:

Post a Comment