This project is read-only.
Basic Discriminated Unions

Defining Types
Description: Discriminated unions give a way of building types from the disjoint union of two or more existing types. This sample shows how to build one such type and how to decompose its values.
type wheel = Wheel of float  // radius of wheel, inches
type cycle =
| Unicycle of wheel
| Bicycle of wheel * wheel

let veryBigWheel = Wheel(26.0)
let bigWheel = Wheel(13.0)
let smallWheel = Wheel(6.0)

let pennyFarthing = Bicycle(veryBigWheel, smallWheel)
let racer = Bicycle(bigWheel, bigWheel)
let kidsBike = Bicycle(smallWheel, smallWheel)

let UnionSample1() =
let show bike =
match bike with
| Unicycle (Wheel r) -> printfn "Unicycle, one wheel, radius = %f" r
| Bicycle (Wheel r1,Wheel r2) -> printfn "Bicycle, two wheels, front = %f, back = %f" r1 r2
show pennyFarthing;
show racer;
show kidsBike

Execution Result:
Bicycle, two wheels, front = 26.000000, back = 6.000000
Bicycle, two wheels, front = 13.000000, back = 13.000000
Bicycle, two wheels, front = 6.000000, back = 6.000000

Last edited Sep 14, 2011 at 3:57 AM by ttliu2000, version 1


No comments yet.