Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous recursive function in Scala

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?)

like image 636
aioobe Avatar asked Mar 17 '11 09:03

aioobe


People also ask

Can an anonymous function be recursive?

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.

What is anonymous function in Scala?

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.

What is anonymous lambda function in Scala?

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.


2 Answers

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.

like image 111
Rustem Suniev Avatar answered Oct 16 '22 05:10

Rustem Suniev


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) } 
like image 42
Spangaer Avatar answered Oct 16 '22 04:10

Spangaer