forward reference extends over definition of value - scala

I'm learning nested functions in Scala and here is some code I'm having trouble with
object Main extends App {
val fac = (x: Int) => {
val factorial: (Int, Int) => Int = (x, accum) => if (x == 1) accum else factorial(x-1, accum*x)
factorial(x,1)
}
println(fac(3))
}
the compiler gives this error:
forward reference extends over definition of value factorial
val factorial: (Int, Int) => Int = (x, accum) => if (x == 1) accum else factorial(x-1, accum*x)**
what am I doing wrong?

You should declare factorial using def and not val:
Using val means it's a value, evaluated once, at declaration; Therefore, it's easy to see why the compiler can't use that definition while evaluating it
Using def means it's a method, evaluated separately for every call, therefore supporting referencing itself within the definition (recursion)
Perhaps a less-confusing way to write this would be to declare this method as a method that expects arguments, instead of a method that returns a function which expects these arguments:
val fac = (x: Int) => {
def factorial(x: Int, accum: Int): Int = if (x == 1) accum else factorial(x-1, accum*x)
factorial(x,1)
}

Related

Missing parameter type for expanded function with underscore

I'm trying to make function that compose itself -
def genericComposition[T](f: T => T, g: T => T) = {
def call(x: T) = g(f(x))
call _
}
def testComposition[T](g: T=>T, n: Int) = {
val call = genericComposition[T](g,g)
def helper(res: T, m: Int) : T = {
if(m == 0) res
else helper(call(res), dec(m))
}
helper(_,n)
}
This should call composition of f with f (f(f(x)) n times, non generic version, where all T's are Int or Double, etc works fine, but when I try to make generic version I use underscore to pass x as parameter to the helper function, but have error:
Error:(26, 11) missing parameter type for expanded function ((x$1:
) => helper(x$1, n)) helper(_,n)
^
In my experience, the _ syntactic sugar is a bit finicky. Scala's type inference is not perfect. It works in simple cases, but in some more subtle cases sometimes you have to provide it with type information yourself. Perhaps someone else can explain why that's the case here.
If you specify the return type of your function, it fixes the issue. And this is often considered good style anyway:
def testComposition[T](g: T=>T, n: Int): T => T = {
...
helper(_,n)
}
Please check if this is what you need
def testComposition[T](g: T=>T, n: Int) = {
val call = genericComposition[T](g,g)
def helper( m: Int,res: T) : T = { //changed order of parameters
if(m == 0) res
else helper(dec(m),call(res))
}
(helper _).curried(n) // now we can make it carried
}
println(testComposition[Int](x=>x+1,5)(5))

Invoking higher order functions - Scala

Hi I am new to Scala and trying to call a higher order function sum_of from main class.I am getting "Cannot resolve reference sumOf with such signature error".
object SumOf {
def main(args: Array[String]) {
val y = sumOf(x=>x ,4,5)
println(y)
}
def sumOf(f: Int => Int)(a: Int, b: Int): Int = {
def loop(a: Int, acc: Int): Int =
if (a > b) acc
else loop(a + 1, f(a) + acc)
loop(a, 0)
}
}
sumOf is a curried function so it takes two arguments in the form of sumOf(x => x)(4,5) which is different from sumOf(x => x, 4,5). This is the reason you are getting an error.
Further, you can call it with only one argument sumOf(x => x) _ which returns another function that takes the second argument
(Int, Int) => Int = <function2> and return a function. This is more commonly known as partial function application.
Your sumOf method has two argument lists, and needs to be called with two argument lists.
val y = sumOf(x => x)(4, 5)
You can think of sumOf as a function which takes an Int => Int and returns a new function, which takes two Ints to return an Int.

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)

Which ways to introduce a new variable in Scala exist?

It is well-known that a programmer can declare a new variable in Scala by using val or var, like this:
val x = 10 //x is now defined and an Integer.
A function parameter also introduces a new variable:
def fun(y: String) {
//y of type String is now available here
}
These are straight forward examples. However, there are more ways to declare a variable in a given context.
For instance, a match expression can also introduce new variables:
val z = 10
z match {
case w: Int => w //w is a valid variable of type Int in this scope
}
What are further commands which introduce variables into a certain scope in Scala?
Background for the interested:
I'm using this in a macro which finds variable definitions (ValDefs) in the abstract syntax tree. match expressions or function definitions generate a different syntax tree than normal ValDefs, which I have to take care of. Since I want my macro to be robust, I want to test it against all possible forms of variable declarations.
Notes on comments:
Method definitions with def are not of concern. Furthermore, I am only interested in variables which are visible in the source code and can be referenced by some term.
Here's a list of everything I know of that might be different; x is the variable created:
// Within a block
val x = 5
var x = 5
lazy val x = 5
def x = 5
object x { val value = 5 }
val MyCaseClass(x, _) = oneOfMyCaseClasses
val MyCaseClass(_, Another(x)) = foo
val MyCaseClass(_, x # Another(_)) = foo
// Functions
m.map( x => bar(x) )
m.map( (x: Int) => bar(x) )
// Functions that destructure
m.map{ case y if foo(y) => baz; case x => bar(x) }
m.map{ case Option(x) => bar(x) }
m.map{ case Option(List(x)) => bar(x) }
m.map{ case Option(x # List(_)) => foo(x) }
// Partial functions with/without destructuring
m.collect{ case x => bar(x) }
m.collect{ case Option(List(x)) => bar(x) }
m.collect{ case Option(x # List(_)) => foo(x) }
// For comprehensions
for (x <- xs)
for (y <- ys; x = foo(y))
for ((x, _) <- zs)
for ((_, y # Option(_)) <- ws)
// Method arguments
def foo(x: Int) =
def foo(y: Int)(implicit x: Foo) =
class Foo(x: Int)
class Foo(val x: Int)
class Foo(var x: Int)
case class Foo(x: Int)
case class Foo(var x: Int)
Destructuring Bind:
case class CaseClassFiftyThree(x: Double, y: Long, z: String)
...
someValue match { case CaseClassFiftyThree(x, y, z) =>
/* x, y and z are bound here as Double, Long and String, resp. */ }
Irrefutable Pattern Match:
val (r, s, t) = (53, 17.0 * 3 + 2, "LIII")
/* r, s and t are bound here as Int, Double and String, resp. */

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