Created
June 30, 2010 10:18
-
-
Save forki/458489 to your computer and use it in GitHub Desktop.
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
type OptionBuilder() = | |
member b.Delay(f) = f() | |
member b.Return(x) = | |
match x with | |
| None -> None | |
| Some r -> Some(r) | |
member b.Bind(p,rest) = | |
match p with | |
| None -> None | |
| Some r -> rest r | |
let maybe = OptionBuilder() | |
//Sample dictionaries | |
let fullNamesDb = Map.ofSeq(seq{ | |
yield ("Bill Gates", "billg@microsoft.com") | |
yield ("Bill Clinton", "bill@hope.ar.us") | |
yield ("Michael Jackson", "mj@wonderland.org") | |
yield ("No Pref Guy", "guy@nopref.org") | |
}) | |
let nickNamesDb = Map.ofSeq(seq{ | |
yield ("billy", "billg@microsoft.com") | |
yield ("slick willy", "bill@hope.ar.us") | |
yield ("jacko", "mj@wonderland.org") | |
}) | |
let prefsDb = Map.ofSeq(seq{ | |
yield ("billg@microsoft.com", "HTML") | |
yield ("bill@hope.ar.us", "Plain") | |
yield ("mj@wonderland.org", "HTML") | |
}) | |
let mplus m1 m2 = if m1 <> None then m1 else m2 // TODO: As combine function in Builder? | |
let (+) = mplus | |
let lookUp name = maybe{ | |
let! combined = fullNamesDb.TryFind name + nickNamesDb.TryFind name | |
return prefsDb.TryFind combined | |
} | |
let billGatesPref = lookUp "Bill Gates" |> printfn "%A" // Some "HTML" | |
let billyPref = lookUp "billy" |> printfn "%A" // Some "HTML" | |
let billClintonPref = lookUp "Bill Clinton" |> printfn "%A" // Some "Plain" | |
let steffenPref = lookUp "Steffen" |> printfn "%A" // None | |
let noPref = lookUp "No Pref Guy" |> printfn "%A" // None | |
System.Console.ReadKey() |> ignore |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Lazy alternative: http://gist.github.com/458504
Maybe we should build a lazy maybe for this sample.