Skip to content

Instantly share code, notes, and snippets.

@forki
Created June 30, 2010 10:18
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 forki/458489 to your computer and use it in GitHub Desktop.
Save forki/458489 to your computer and use it in GitHub Desktop.
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
@forki
Copy link
Author

forki commented Jun 30, 2010

Lazy alternative: http://gist.github.com/458504

Maybe we should build a lazy maybe for this sample.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment