Created
May 20, 2015 14:31
-
-
Save AndyDentFree/46ac476a31b07d103a03 to your computer and use it in GitHub Desktop.
Working example (from Xamarin Studio) demonstrating Type Variants and discriminated unions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
*) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.