Anonymous recursive function in Scala - 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?)

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

in order to make it look geekier you can also use this code style:
val fact = new ((Int) => Int){
def apply(x:Int):Int = if(x==1) x else x * apply(x-1)
}

Adding to the many good responses here in this thread, the fact that Scala is not giving us tail call optimizable Fixed-point combinator has been bothering me so much so that I've decided to write a macro to translate Y-combinator-like call to an ordinary, idiomatic recursive call (with tail call optimization, of course). The idea is that a call like
fix[Int,Int]((next) => (y) => ...body...)
is readily translatable into
({(input) =>
object next {
def apply(y:Int):Int = ...body...
}
next(input)
})
I've put up macro implementation targeting Scala 2.11 (with minor tweak should also work with 2.10) into this gist.
With this macro, we can perform ordinary recursive tasks in anonymous manner without fearing stack overflow e.g.
import asia.blip.ymacro.YMacro._
(y[BigInt,BigInt]((xx) => (y) => if(y==1) 1 else y * xx(y-1)))(2000)
gives
res0: BigInt = 33162750924506332411753933805763240382811...

Recursive calls on Scala.
Let me take sum of N numbers example for recursion
var sumIt:(Int => Int) = (x: Int) => {if(x<=1) 1 else sumIt(x-1)+x}
scala> sumIt(10)
val res141: Int = 55
You can see the sumIt has its type with Int, Int as Input and the return value. The sumIt lambda function takes as argument which is an Integer and it does recursive call on sumIt.
I just this example for easy understanding the recursion call. You can direct formula for this logic like...
sumValue = (N*(N+1)) /2

A very simple approach:
val fact = { (x: Int) =>
def f(x: Int): Int = if (x == 0) 1 else x * f(x-1)
f(x)
}
// Use as anonymous function below
(1 to 5).map { (x: Int) =>
def f(x: Int): Int = if (x == 0) 1 else x * f(x-1)
f(x)
}
// res0: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 6, 24, 120)

Related

Can someone please expand the following shorthand and explain how this works

I'm looking at this sample code and after entering it in the scala repl I can see how it works.
val twice: Int => Int =
x => x * 2
This is similar:
val parse: String => Option[Int] =
s => if(s.matches("-?[0-9]+")) Some(s.toInt) else None
Can someone please deconstruct the above method and explain how this works?
I can see the name twice or parse, followed by the type which is Int => Int or String => Option[Int].
Now in the 2nd line of both functions you have a variable x or s. I can only assume this is the parameter.
Also if you can expand on what scala features allow a function to be written like this.
Thanks!
The expected type of value
x => x * 2
is
Int => Int
which de-sugars to
Function1[Int, Int]
hence function definition
val twice: Int => Int = x => x * 2
is equivalent to
val twice: Function1[Int, Int] = new Function1[Int, Int] {
override def apply(x: Int) = x * 2
}
as per SLS 6.3 Anonymous Functions.

Addressing parameter function's parameter in a scala method

It's probably obvious, but it's making me crazy and I think my code is being bloated as a result (missing the obvious, not the making me crazy part).
I have a method as follows:
def fun(f: Int => Boolean, y: Int): Int
This method is going to be called like this fun(*some anon func*, y) and should increase and return y + 1 when some anon function (applied to some param) is greater than 0 and y - 1 otherwise. How to define fun? I'm trying something like
def fun(f: Int => Boolean, y: Int): Int =
if (f) y - 1
else y + 1
Obviously, that doesn't work. I should put f(tmp), where tmp:Int but I'm now sure how to express that.
All examples I could find online always apply f on y, but this is just funny.
Update: here's a similar problem I have already solved, but am not happy with how did I do it:
For a given function forall(s: Set, p: Int => Boolean): Boolean, which returns true iff all the set elements x in S (def S: int => Boolean, indicator function for set S) satisfy p(x), create a function that will implement exists quantifier (exists function). In set theory, one can express this quantifier as (in terms of the problem described above) not all elements (not forall) of a set satisfy NOT p.
I did something like this:
def exists(s: Set, p: Int => Boolean): Boolean = {
def negP(x: Int): Boolean = !p(x)
!forall(s, negP)
}
My question is: how to do this without defining negP? I cannot state !p because Scala gives error for ! operator. I cannot use !p(x) because there is no x. Hence the problem above and my question.
TIA
You could make it return a function that does that, like so:
def fun(f: Int => Int, y: Int): Int => Int =
input => if (f(input) > 0) y - 1 else y + 1
val test1 = fun(x => x*2, 1)
println(test1(-1)) // "2"
val test2 = fun(x => x - 100, 5)
println(test2(101)) // "4"
val test3 = fun(x => x, -10)
println(test3(0)) // "-9"
EDIT: Note that I changed the signature of the input function, as I think it probably reflects the requirements better, changing it back to boolean should be trivial(see other answers). :)
EDIT(2):
Seeing is you updated your question, I thought best to update my answer: You can always just inline a function, in your example, maybe you could do it like this:
def exists(s: Set, p: Int => Boolean): Boolean = !forall(s, x => !p(x))
Your original problem can't be solved because you can't test the output of f() without invoking f(), and you can't invoke f() without an input argument to pass. I think the best you can hope for is something like this.
def fun(f: Int => Boolean, y: Int): Int => Int = (arg: Int) =>
if (f(arg)) y - 1
else y + 1
Your "similar problem" looks to me like it should be a different question.
Your proposed solution can be solved via recursion, but using forall() it can be expressed more concisely.
def exists(s: Set[Int], p: Int => Boolean): Boolean =
!forall(s, (x:Int) => !p(x))
It sounds like you don't actually want to pass a parameter to your anonymous function? Then try this:
def fun(f: () => Boolean, y: Int): Int =
if (f()) y - 1
else y + 1

Why should calling a currying function with non-complete args with underscore

According to ScalaByExample:
A curried function definition def f (args1) ... (argsn) = E where n >
1 expands to
def f (args1) ... (argsn−1) = { def g (argsn) = E ; g }
Or, shorter, using an anonymous function:
def f (args1) ... (argsn−1) = ( argsn ) => E
Uncurried version:
def f(x: Int): Int => Int = {
y: Int => x * y
} //> f: (x: Int)Int => Int
def f1 = f(10) //> f1: => Int => Int
f1(5)
Curried version:
def g(x: Int)(y: Int) = {
x * y
} //> g: (x: Int)(y: Int)Int
def g1 = g(10) _ //> g1: => Int => Int
g1(5)
The question is, Why curried required the underscore in line #5 in the second code snippet.
You can find the explanation at Martin Odersky book: http://www.artima.com/pins1ed/functions-and-closures.html (search for "Why the trailing underscore").
In short this is because Scala is closer to Java in a lot of things, rather than functional languages where this is not required. This helps you to find out mistakes at compile time, if you forgot the missing argument.
If underscore was not required, the next code will compile:
println(g(10))
And this check helps you preventing such mistakes
There are some cases though, when such calls are obvious, and underscore is not required:
def g(x: Int)(y: Int) = {
x * y
}
def d(f: Int => Int) {
f(5)
}
d(g(10)) // No need to write d(g(2) _)
// Or any other way you can specify the correct type
val p: Int => Int = g(10)
Something to note: in Scala, def's are methods, not functions, at least, not directly. Methods are converted to functions by the compiler every time a method is used where a function would be required, but strictly speaking, a function would be created with val instead, like so:
val curry = (x: Int) => (y: Int) => x * y
This allows you to apply arguments one at a time without having to add a trailing underscore. It functions identically to the code in your first snippet, but because it uses val and not def, curry cannot be written like
val curry(x: Int) = (y: Int) => x * y //Won't compile
So, when you want to write a function that behaves the way you want a curried function to behave, write it like I did in my first snippet. You can keep chaining parameters with => as many times as you want (up to technical limits, but good luck hitting them).

Tail recursion: internal "loop" function or default values for accumulators

I know of at least two styles to writing tail recursive functions. Take a sum function for example:
def sum1(xs: List[Int]): Int = {
def loop(xs: List[Int], acc: Int): Int = xs match {
case Nil => acc
case x :: xs1 => loop(xs1, acc + x)
}
loop(xs, 0)
}
vs
def sum2(xs: List[Int], acc: Int = 0): Int = xs match {
case Nil => acc
case x :: xs1 => sum2(xs1, x + acc)
}
I've noticed the first style (internal loop function) much more commonly than the second. Is there any reason to prefer it or is the difference just a matter of style?
There a couple of reasons to prefer the first notation.
Firstly, you define clearly to your reader what's the internal implementation from the external one.
Secondly, in your example the seed value is a pretty simple one that you can put straight as a default argument, but your seed value may be a very complicated-to-compute object that requires a longer init than default. Should this init for example require to be done asynchronously, you definitely want to put it out of your default value and manage with Futures or w/e.
Lastly, as Didier mentioned, the type of sum1 is a function from List[Int] -> Int (which makes sense), while the type of sum2 is a function from (List[Int], Int) -> Int which is less meaningful. Also, this implies that it's easier to pass sum1 around than sum2. For example, if you have an object that encapsulates a list of Int's and you want to provide synthesizer functions over it you can do (pseudocode, i dont have a repl to write it properly now):
class MyFancyList[T](val seed: List[T]) = {
type SyntFunction = (List[T] => Any)
var functions = Set[SyntFunction]
def addFunction(f: SyntFunction) = functions += f
def computeAll = {
for {
f <- functions
}
yield {
f(seed)
}
}
}
And you can do:
def concatStrings(list:List[Int]) = {
val listOfStrings = for {
n <- list
}
yield {
n+""
}
listOfStrings.mkString
}
val x = MyFancyList(List(1, 2, 3))
x.addFunction(sum1)
x.addFunction(concatStrings)
x.computeAll == List(6, "123")
but you can't add sum2 (not as easily at least)

Usefulness (as in practical applications) of Currying v.s. Partial Application in Scala

I'm trying to understand the advantages of currying over partial applications in Scala. Please consider the following code:
def sum(f: Int => Int) = (a: Int, b: Int) => f(a) + f(b)
def sum2(f: Int => Int, a: Int, b: Int): Int = f(a) + f(b)
def sum3(f: Int => Int)(a: Int, b: Int): Int = f(a) + f(b)
val ho = sum({identity})
val partial = sum2({ identity }, _, _)
val currying = sum3({ identity })
val a = currying(2, 2)
val b = partial(2, 2)
val c = ho(2, 2)
So, if I can calculate partially applied function that easy, what are the advantages of currying?
Currying is mostly used if the second parameter section is a function or a by name parameter. This has two advantages. First, the function argument can then look like a code block enclosed in braces. E.g.
using(new File(name)) { f =>
...
}
This reads better than the uncurried alternative:
using(new File(name), f => {
...
})
Second, and more importantly, type inference can usually figure out the function's parameter type, so it does not have to be given at the call site.
For instance, if I define a max function over lists like this:
def max[T](xs: List[T])(compare: (T, T) => Boolean)
I can call it like this:
max(List(1, -3, 43, 0)) ((x, y) => x < y)
or even shorter:
max(List(1, -3, 43, 0)) (_ < _)
If I defined max as an uncurried function, this would not work, I'd have to call it like this:
max(List(1, -3, 43, 0), (x: Int, y: Int) => x < y)
If the last parameter is not a function or by-name parameter, I would not advise currying. Scala's _ notatation is amost as lightweight, more flexible, and IMO clearer.
I think it becomes clearer if you invert your curried example:
def sum4(a: Int, b: Int)(f: Int => Int): Int = f(a) + f(b)
val d = sum4(2, 2) { x =>
x * x
}
It is more of an optical effect but you don’t need to use any parentheses around the whole expression. Of course you can achieve the same result using partial application or by creating a helper method to invert the arguments, sure. The point is, that you don’t have to do all of this if you start with a curried method in the first place. In that sense currying is more of an API and syntax sugar thing. It is not expected that you use
val partial_sum4 = sum4(2, 2)
anywhere in your code or that this is in any way especially meaningful to do. It is just that you get a nicely looking expression easily.
(Well, and there are some advantages with respect to type inference…)