Is there a way to write an anonymous function that is recursive in Scala? I'm thinking of something like this:
((t: Tree) => { print(t.value); for (c <- t.children) thisMethod(c) })(root)
(Related question: Which languages support *recursive* function literals / anonymous functions?)
Anonymous recursion is primarily of use in allowing recursion for anonymous functions, particularly when they form closures or are used as callbacks, to avoid having to bind the name of the function. Anonymous recursion primarily consists of calling "the current function", which results in direct recursion.
In Scala, An anonymous function is also known as a function literal. A function which does not contain a name is known as an anonymous function. An anonymous function provides a lightweight function definition. It is useful when we want to create an inline function.
Scala lambda functions are anonymous functions. They reduce the line of code and make the function more readable and convenient to define. We can also reuse them. We can use this lambda function to iterate our collection data structure and performed any kind of operation on them.
As described in the link you posted. You can use Y-combinator. Here is example:
scala> def fix[A,B](f: (A=>B)=>(A=>B)): A=>B = f(fix(f))(_) fix: [A,B](f: ((A) => B) => (A) => B)(A) => B scala> val fact = fix[Int,Int](f => a => if(a<=0) 1 else f(a-1) * a) fact: (Int) => Int = <function1> scala> fact(12) res0: Int = 479001600
Note it doesn't work with big numbers. Be careful with tail call optimization.
If you don't want to hit the "Amazing mathematics" you could just revert to the object aspects of scala.
val fact = new Function1[Int,Int]{ def apply(x:Int):Int = if(x==1) x else x * apply(x-1) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With