Adding to the many good answers here in this thread, the fact that Scala does not give us an optimized fixed-point tail combinator has bothered me so much that I decided to write a macro to translate Y-combinator a similar call to a regular, idiomatic recursive call ( Of course, with tail call optimization). The idea is that a call like
fix[Int,Int]((next) => (y) => ...body...)
easily translates to
({(input) => object next { def apply(y:Int):Int = ...body... } next(input) })
I applied the implementation of the Scala 2.11 macro (with a slight change should also work with 2.10) in this sense .
With this macro, we can perform ordinary recursive tasks anonymously without fear, for example.
import asia.blip.ymacro.YMacro._ (y[BigInt,BigInt]((xx) => (y) => if(y==1) 1 else y * xx(y-1)))(2000)
gives
res0: BigInt = 33162750924506332411753933805763240382811...
In-Ho Yi 03 Sep '14 at 10:49 2014-09-03 10:49
source share