Can you implement CPS using computation expressions in F#?
Brian McNamara's blog gives this solution:
type ContinuationBuilder() =
member this.Return(x) = (fun k -> k x)
member this.ReturnFrom(x) = x
member this.Bind(m,f) = (fun k -> m (fun a -> f a k))
member this.Delay(f) = f()
let cps = ContinuationBuilder()
Looks good. I can write List.map
in CPS:
let rec mapk f xs = cps {
match xs with
| [] -> return []
| x::xs ->
let! xs = mapk f xs
return f x::xs
}
But it stack overflows:
mapk ((+) 1) [1..1000000] id
What am I doing wrong?