-
-
Save mausch/2276291 to your computer and use it in GitHub Desktop.
A VERY simple application scenario of the Maybe Monad in F#
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 FSharpx | |
/// Type synonyms | |
type ProductId = string | |
type Price = float | |
type Inventory() = | |
let inv_ = new System.Collections.Generic.Dictionary<ProductId, Price>() | |
member this.Stock id price = | |
inv_.Add(id, price) | |
member this.Price id = | |
inv_ |> Dictionary.tryFind id | |
let inline (|@|) a b = Option.lift2 (+) a b | |
let reporter = | |
function | |
| Some p -> printfn "Total price: %g." p | |
| None -> printfn "One or more id not found." | |
//Initialize a basic inventory and throw inside a bunch of items | |
let inventory = Inventory() | |
inventory.Stock "MyWidget" 10.3 | |
inventory.Stock "Gizmos" 4.34 | |
inventory.Stock "Foo1000" 8.12 | |
//Sum prices | |
inventory.Price("MyWidget") |@| inventory.Price("Gizmos") |> reporter | |
inventory.Price("MyWidget") |@| inventory.Price("Gizmos") |@| inventory.Price("Foo1000") |> reporter | |
//A failing computation | |
inventory.Price("MyWidget") |@| inventory.Price("Gizmos") |@| inventory.Price("DoesNotExist") |> reporter | |
//A completely automatic procedure | |
let sumAndReport (inventory : Inventory) ids = | |
let basket = Seq.map (fun pid -> inventory.Price(pid)) ids | |
Seq.reduce (|@|) basket |> reporter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment