Created
June 30, 2010 10:38
-
-
Save forki/458504 to your computer and use it in GitHub Desktop.
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
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 | |
member b.Combine m1 m2 = if m1 <> None then m1 else m2 | |
let maybe = OptionBuilder() | |
//Sample dictionaries | |
let fullNamesDb = Map.ofSeq(seq{ | |
yield ("Bill Gates", "[email protected]") | |
yield ("Bill Clinton", "[email protected]") | |
yield ("Michael Jackson", "[email protected]") | |
yield ("No Pref Guy", "[email protected]") | |
}) | |
let nickNamesDb = Map.ofSeq(seq{ | |
yield ("billy", "[email protected]") | |
yield ("slick willy", "[email protected]") | |
yield ("jacko", "[email protected]") | |
}) | |
let prefsDb = Map.ofSeq(seq{ | |
yield ("[email protected]", "HTML") | |
yield ("[email protected]", "Plain") | |
yield ("[email protected]", "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 + fun _ -> 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