Skip to content

Instantly share code, notes, and snippets.

@nojaf
Created August 9, 2017 06:51
Show Gist options
  • Save nojaf/37862913b4ac90bb45a578f60bddca17 to your computer and use it in GitHub Desktop.
Save nojaf/37862913b4ac90bb45a578f60bddca17 to your computer and use it in GitHub Desktop.
F# Computation Expressions
open System
let divideBy bottom top =
if bottom = 0
then None
else Some(top/bottom)
type MaybeBuilder() =
member this.Bind(x, f) =
printfn "x: %A, f: %A" x f
match x with
| None -> None
| Some a -> f a
member this.Return(x) =
Some x
let maybe = new MaybeBuilder()
let divideByWorkflow init x y z =
printfn "x %A" x
maybe
{
let! a = init |> divideBy x
let! b = a |> divideBy y
let! c = b |> divideBy z
return c
}
let good = divideByWorkflow 12 3 2 1
let pipeInto (someExpression,lambda) =
match someExpression with
| None ->
None
| Some x ->
x |> lambda
let return' c = Some c
let divideByWorkflowPiped x y w z =
pipeInto (x |> divideBy y, fun a ->
pipeInto (a |> divideBy w, fun b ->
pipeInto (b |> divideBy z, fun c ->
return' c
)))
let goodPipe = divideByWorkflowPiped 12 3 2 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment