Skip to content

Instantly share code, notes, and snippets.

@moccos
Last active December 16, 2015 18:39
Show Gist options
  • Save moccos/5479239 to your computer and use it in GitHub Desktop.
Save moccos/5479239 to your computer and use it in GitHub Desktop.
F# computation expression practice.
type OptionReturnBuilder() =
member __.Bind(opt, expr) = opt |> function
| Some x -> Some x
| None -> expr opt
member __.Return(x) = x
member __.ReturnFrom(x) = x
member __.Delay(f): option<_> = f ()
let optionr = OptionReturnBuilder()
let f x = x |> function
| x when x < 0 ->
printfn "%d: None" x
None
| x ->
printfn "%d: Some" x
Some x
// ---
optionr {
let! r1 = f 2
let! r2 = f -2
let! r3 = f 4
return r3
}
// 2: Some
// ---
optionr {
let! r1 = f -2
let! r1 = f -3
return! f 4
}
// -2: None
// -3: None
// 4: Some
let (|FOO|_|) x y = x |> function
| x when x < y ->
printfn "%d < %d: None" x y
None
| x ->
printfn "%d >= %d: Some" x y
Some x
match 10 with
| FOO 5 n -> n
| FOO 15 n -> n
| _ -> -1
// 15
match 20 with
| FOO 5 n -> n
| FOO 15 n -> n
| _ -> -1
// -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment