Tail recursion using lamda

def tailFac : BigInt => BigInt => BigInt = param => accumulator => param match {
    case x if x.intValue == 0 => accumulator
    case _ => tailFac  (param - 1) (accumulator * param)

Why we can not create tail rec by lamda ? Or what is the way ?

Tail-recursion means some method calls itself and then simply returns whatever the call to itself returns. Once you don’t simply return the returned value, but instead use it to create a new value, it is no longer tail-recursion.

In your case, tailFac does not simply return the result of calling itself. Inside tailFac, the call to tailFac returns a lambda object, which is then called and the result of that call is wrapped into a new lambda object. To make it tail recursive, you would have to return the exact lambda object returned by the inner call.

1 Like

Why not just using a normal method? The syntax is cleaner, plus the ability to hide the tail-recursion in an inner method is very useful for things like accumulators.
And then you can create a lambda out of this method if you want.

Finally, if you have a lambda use a val not a def, you do not want to create a new object every time you use it.