【发布时间】:2019-04-08 19:37:41
【问题描述】:
你能在 F# 中使用计算表达式来实现 CPS 吗?
Brian McNamara's blog 给出了这个解决方案:
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()
看起来不错。我可以在 CPS 中写List.map:
let rec mapk f xs = cps {
match xs with
| [] -> return []
| x::xs ->
let! xs = mapk f xs
return f x::xs
}
但是堆栈溢出了:
mapk ((+) 1) [1..1000000] id
我做错了什么?
【问题讨论】:
标签: f# continuation-passing computation-expression