Skip to content

Instantly share code, notes, and snippets.

@danielrbradley
Created December 9, 2016 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielrbradley/baeda02a217b9708996768a8d893e412 to your computer and use it in GitHub Desktop.
Save danielrbradley/baeda02a217b9708996768a8d893e412 to your computer and use it in GitHub Desktop.
3 ways of organising F# functions related to a type
module VendingMachine
type Coin = Quarter | Dime | Nickel
let valueOf coin =
match coin with
| Quarter -> 0.25m
| Dime -> 0.10m
| Nickel -> 0.05m
/// 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 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