Skip to content

Instantly share code, notes, and snippets.

@hodzanassredin
Created January 12, 2016 21:58
Show Gist options
  • Save hodzanassredin/a51825d0bd79664cab69 to your computer and use it in GitHub Desktop.
Save hodzanassredin/a51825d0bd79664cab69 to your computer and use it in GitHub Desktop.
free maybe implementation
type Maybe<'a> =
| Some of 'a
| None
let fmap f m =
match m with
| Some(a) -> Some(f a)
| None -> None
type Free<'a> =
| Pure of 'a
| Free of Maybe<Free<'a>>
type FreeBuilder() =
member x.Bind(v:Free<'a>,f:'a->Free<'b>) =
match v with
| Free(m) -> Free(fmap (fun x' -> x.Bind(x', f)) m)
| Pure(v) -> f(v)
member x.Return v = Pure(v)
let liftFree x = Free (fmap Pure x)
let rec foldFree f x =
match x with
| (Pure a) -> a
| (Free x) -> f (fmap (foldFree f) x)
let free = FreeBuilder()
let none ()= liftFree None
let some x = liftFree(Some(x))
let testfn x = liftFree <| Some(x + 1)
let r = free{
let! a = none()
let! b = testfn a
return a + b
}
let s = foldFree (fun x -> match x with
| Some(x) -> x
| None -> 0) r
printfn "free res is %d" s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment