Skip to content

Instantly share code, notes, and snippets.

@AndyDentFree
Created May 20, 2015 14:31
Show Gist options
  • Save AndyDentFree/46ac476a31b07d103a03 to your computer and use it in GitHub Desktop.
Save AndyDentFree/46ac476a31b07d103a03 to your computer and use it in GitHub Desktop.
Working example (from Xamarin Studio) demonstrating Type Variants and discriminated unions
open Microsoft.FSharp.Math
type Shape =
| Circle of radius:float
| Rectangle of width:float * height:float // tuple of float, float
| Triangle of tbase:float * height:float
let area shape =
match shape with
| Circle radius -> Math.PI * radius * radius
| Rectangle (width, height) -> width * height
| Triangle (tbase, height) -> 0.5 * tbase * height
let cshape = Circle(10.)
printfn "Circle Area: %f" (area cshape)
let rshape = Rectangle(3., 7.)
printfn "Rect Area: %f" (area rshape)
let tshape = Triangle(3., 7.)
printfn "Triangle Area: %f" (area tshape)
(*
Console output for the above
Circle Area: 314.159265
Rect Area: 21.000000
Triangle Area: 10.500000
*)
@AndyDentFree
Copy link
Author

This was my taking the second example from Luketopia's slides on OO vs Discriminated Unions. I just changed it to rename things in case people mis-read his code and renamed a variable base so quoting wasn't necessary.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment