Last active
December 16, 2015 18:39
-
-
Save moccos/5479239 to your computer and use it in GitHub Desktop.
F# computation expression practice.
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 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() |
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
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 |
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
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