F# CPS 评估顺序
我试图在使用F#中使用持续通信样式时了解评估顺序。 以此功能为例。
let rec CPSfunc n k c =
if k = 0 then c 1
else if k > 0 then CPSfunc n (k-1) (fun res -> c(2*res+k))
使用参数运行时第一的。
CPSfunc 4 3 (fun res -> res)
CPSfunc 4 2 (fun res -> fun 2*res+3 -> res)
CPSfunc 4 1 (fun res -> fun 2*res+2 -> fun 2*res+3 -> res)
// Evaluating backwards
fun res -> fun 2*res+2 -> fun 2*res+3 -> 1
fun res -> fun 2*res+2 -> 2*1+3
fun res -> 2*5+2
// Evaluating forward
fun 1 -> fun 2*res+2 -> fun 2*res+3 -> res
fun 2*1+2 -> fun 2*res+3 -> res
fun 2*4+3 -> res
4
如何正确计算正确的输出?
I'm trying to understand the order of evaluation when using Continuation-passing style in F#.
Take this function for example.
let rec CPSfunc n k c =
if k = 0 then c 1
else if k > 0 then CPSfunc n (k-1) (fun res -> c(2*res+k))
When running it with the arguments CPSfunc 4 3 id
it evaluates to 19
, but when I try to evaluate it by hand, I get different results, based on evaluating forward or backwards first.
CPSfunc 4 3 (fun res -> res)
CPSfunc 4 2 (fun res -> fun 2*res+3 -> res)
CPSfunc 4 1 (fun res -> fun 2*res+2 -> fun 2*res+3 -> res)
// Evaluating backwards
fun res -> fun 2*res+2 -> fun 2*res+3 -> 1
fun res -> fun 2*res+2 -> 2*1+3
fun res -> 2*5+2
// Evaluating forward
fun 1 -> fun 2*res+2 -> fun 2*res+3 -> res
fun 2*1+2 -> fun 2*res+3 -> res
fun 2*4+3 -> res
4
How do I properly calculate the correct output?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要看到 19 是正确的结果,我认为最简单的方法是从
k = 0
开始并递增。每个结果只是前一个结果的两倍加上k
。 (请注意,未使用n
。)因此我们有:不过,将简单逻辑转换为延续会变得复杂。下面是 F# 中
CPSfunc 4 3 id
的扩展:PS 要使
c
具有所需的int ->; int
签名,您需要稍微不同地定义CPSfunc
,所以我假设您实际上已经完成了:To see that 19 is the correct result, I think it's easiest to start with
k = 0
and increment. Each result is simply twice the previous result, plusk
. (Note thatn
is not used.) So we have:Converting that simple logic into continuations gets complicated, though. Here's what the expansion looks like in F# for
CPSfunc 4 3 id
:P.S. To make
c
have the desiredint -> int
signature, you need to defineCPSfunc
slightly differently, so that's what I assume you've actually done:实际上,我通过对上述功能进行评估,在对它们进行实际评估之前评估了一些功能,从而获得了一些自由,但这并不重要
actually ive taken some liberties by evaluating some functions in the above before they would actually be evaluated, but it doesnt really matter