Skip to content

Instantly share code, notes, and snippets.

@scott-fleischman
Created March 4, 2016 00:56
Show Gist options
  • Save scott-fleischman/4e0206319adee86afa47 to your computer and use it in GitHub Desktop.
Save scott-fleischman/4e0206319adee86afa47 to your computer and use it in GitHub Desktop.
F# for fun and profit - Computation Expressions - Bind exercise - http://fsharpforfunandprofit.com/posts/computation-expressions-bind/
// Exercises from http://fsharpforfunandprofit.com/posts/computation-expressions-bind/
// Part 1
let strToInt str =
match System.Int32.TryParse str with
| (false, _) -> None
| (true, x) -> Some x
type YourWorkflowBuilder() =
member this.Bind(x, f) = Option.bind f x
member this.Return(x) = Some x
let yourWorkflow = new YourWorkflowBuilder()
let stringAddWorkflow x y z =
yourWorkflow
{
let! a = strToInt x
let! b = strToInt y
let! c = strToInt z
return a + b + c
}
// test
let good = stringAddWorkflow "12" "3" "2"
let bad = stringAddWorkflow "12" "xyz" "2"
// Part 2
let strAdd str i = strToInt str |> Option.bind ((+) i >> Some)
let (>>=) m f = Option.bind f m
let good' = strToInt "1" >>= strAdd "2" >>= strAdd "3"
let bad' = strToInt "1" >>= strAdd "xyz" >>= strAdd "3"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment