Skip to content

Instantly share code, notes, and snippets.

@eiriktsarpalis
Created December 25, 2015 22:40
Show Gist options
  • Save eiriktsarpalis/3f75bb812ca265dd14ec to your computer and use it in GitHub Desktop.
Save eiriktsarpalis/3f75bb812ca265dd14ec to your computer and use it in GitHub Desktop.
type Cont<'T> = ('T -> unit) -> (exn -> unit) -> unit
let ret t = fun sc _ -> sc t
let (>>=) f g =
fun sc ec ->
let sc' (t : 'T) =
match (try Choice1Of2 (g t) with e -> Choice2Of2 e) with
| Choice1Of2 g -> g sc ec
| Choice2Of2 e -> ec e
f sc' ec
type ContBuilder() =
member __.Zero() = ret ()
member __.Return t = ret t
member __.Bind(f : Cont<'T>, g : 'T -> Cont<'S>) : Cont<'S> = f >>= g
member __.Delay(f : unit -> Cont<'T>) : Cont<'T> = ret () >>= f
let run (cont : Cont<'T>) =
let result = ref Unchecked.defaultof<'T>
cont (fun t -> result := t) raise
!result
let cont = new ContBuilder()
/// test the implementation
let rec factorial n = cont {
if n = 0 then return failwith "bug!"
else
let! pd = factorial (n-1)
return n * pd
}
run (factorial 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment