Created
December 9, 2016 15:53
-
-
Save danielrbradley/baeda02a217b9708996768a8d893e412 to your computer and use it in GitHub Desktop.
3 ways of organising F# functions related to a type
This file contains hidden or 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
module VendingMachine | |
type Coin = Quarter | Dime | Nickel | |
let valueOf coin = | |
match coin with | |
| Quarter -> 0.25m | |
| Dime -> 0.10m | |
| Nickel -> 0.05m |
This file contains hidden or 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
/// Easier to discover as you can just type a '.' in VS to see options. | |
/// Downside - '.' breaks the type inference :( | |
module VendingMachine | |
type Coin = | |
| Quarter | |
| Dime | |
| Nickel | |
member this.Value = | |
match this with | |
| Quarter -> 0.25m | |
| Dime -> 0.10m | |
| Nickel -> 0.05m |
This file contains hidden or 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
/// This is a common pattern for F# libraries to follow - to keep the type simple, | |
/// but make it easy to find associated functions, and gives good type inference. | |
module VendingMachine | |
type Coin = Quarter | Dime | Nickel | |
// The attribute lets us use the same name as the type. | |
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>] | |
module Coin = | |
let value coin = | |
match coin with | |
| Quarter -> 0.25m | |
| Dime -> 0.10m | |
| Nickel -> 0.05m |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment