Discriminated Union can take arguments, differently.
It's the sample from the book "Professional F# 2.0".
type Color =Both RGB and CMYK take arguments, and these take different arguments (both arity and type).
| Black
| Blue
| Cyan
| Gray
| Green
| Magenta
| DarkBlue
| Red
| White
| Yellow
| RGB of int * int * int
| CMYK of float * float * float * float
> 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