Skip to content

Instantly share code, notes, and snippets.

@matejsarlija
Created October 4, 2021 19:47
Show Gist options
  • Save matejsarlija/988e21dbce534851f8cb20e2d8bdeafa to your computer and use it in GitHub Desktop.
Save matejsarlija/988e21dbce534851f8cb20e2d8bdeafa to your computer and use it in GitHub Desktop.
Solution to Scott Wlaschin's "Introducing bind" chapter from "F# for fun and profit"
module MyBind
open System
let strToInt (str: string) =
try
str |> int |> Some
with
| :? FormatException -> None
let strAdd (str: string) i =
match strToInt str with
| None -> 0 + i
| Some str -> str + i
|> Some
let (>>=) m f = Option.bind f m
type StrToIntMonadBuilder() =
member this.Bind(m, f) =
match m with
| None -> None
| Some a -> f a
member this.Return(m) = Some m
let stringWorkflow = StrToIntMonadBuilder()
let stringAddWorkflow x y z =
stringWorkflow {
let! a = strToInt x
let! b = strToInt y
let! c = strToInt z
return a + b + c
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment