Tail-recursion and scalaz promises
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
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 to repeat
will occur in a different process.
In slightly more terse terms, Promise
is a continuation monad, and flatMap
calls are automatically translated to continuation-passing style for you.
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.
精彩评论