尾递归和 scalaz Promise
我目前正在玩 Scalaz 非阻塞 future 又名。承诺。我正在努力使以下函数尾递归:
@tailrec
private def repeat( res: Promise[I] ):Promise[I] =
res map p flatMap {
(b:Boolean) =>
if( b ) repeat( res flatMap f ) else res
}
其中 p
是类型为 I=>Boolean
的谓词,而 f
是并发功能与 输入I=>Promise[I]
。
该方法无需注释即可编译。
有什么提示吗?谢谢
I am currently playing with Scalaz non-blocking futures aka. Promises. I am struggling to make the following function tail-recursive:
@tailrec
private def repeat( res: Promise[I] ):Promise[I] =
res map p flatMap {
(b:Boolean) =>
if( b ) repeat( res flatMap f ) else res
}
where p
is a predicate with type I=>Boolean
and f
is a concurrent function with
type I=>Promise[I]
.
The method compiles without the annotation.
Any hints ? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的方法根本不是递归的。 res 是可能在另一个线程中运行的计算。
res map p flatMap f
就您的方法而言,将立即返回一个承诺。重复repeat
将在不同的过程中发生。用更简洁的术语来说,
Promise
是一个延续 monad,并且flatMap
调用会自动为您转换为延续传递样式。Your method isn't recursive at all.
res
is a computation potentially running in another thread.res map p flatMap f
will immediately return a promise as far as your method is concerned. The recurrence torepeat
will occur in a different process.In slightly more terse terms,
Promise
is a continuation monad, andflatMap
calls are automatically translated to continuation-passing style for you.虽然这看起来是尾递归,因为该调用在代码中只出现一次,但您有多个递归调用 - 集合中的每个元素都有一个递归调用。至少编译器是这样看到的。 (假设这是某个集合上的 flatMap;我不知道
p
返回什么)您将递归作为匿名函数传递到某个地方。没有人知道它会被执行多久。
Although this looks tail recursive because the call appears only once in code, you have more than one recursive call - one for each element inside your collection. At least that's what the compiler sees. (Supposing this is a flatMap on some collection; I have no idea what
p
does return)You pass the recursion to somewhere as an anonymous function. No one knows how often it will be executed.