0

I am trying to define a recursive lambda expression in scala and struggling a bit with sintax, if think that this is just a syntax: Here is what I have so far (not compilable):

type rec = (Int => Int, Int)
val f = (x : Int) => x + x
val y : rec = (f:Int => Int, x:Int) => if (x > 0) y( f, 1) else 1

Error I am getting: 
ScalaFiddle.scala:14: error: ScalaFiddle.rec does not take parameters
  val y : rec = (f:Int => Int, x:Int) => if (x > 0) y( f, 1) else 1
                                                 ^

Original code sample I am trying to optimize (which works fine):

case class Rec[I, O](fn : (I => O, I) => O) extends (I => O) {
  def apply(v : I) = fn(this, v)
}

val sum = Rec[Int, Int]((f, v) => if (v == 0) 0 else v + f(v - 1))

Any help would be appreciated.

Thanks

Pavel
  • 1,519
  • 21
  • 29
  • 1
    rec is a tuple of a Int => Int function and a integer. by `y(f,1)` you are trying to call a function on a tuple. tuple doesnt have a apply function defined on it. – rogue-one May 23 '17 at 14:39
  • so, does that means that I have to follow original code sample way? to define apply in the type ? or I can do this in the lambda some how? – Pavel May 23 '17 at 14:43
  • yes your original code sample is type complaint. you should follow that approach. The original code is quite optimized let us know what further optimization you are looking for – rogue-one May 23 '17 at 14:49
  • so, as I understand I can NOT extend tuple within lambda expression? so this has to be expresses separately? thats ok then – Pavel May 23 '17 at 14:53
  • updated my answer that corrects your type rec definition – rogue-one May 23 '17 at 14:56
  • Does this answer your question? [Anonymous recursive function in Scala](https://stackoverflow.com/questions/5337464/anonymous-recursive-function-in-scala) – dboy May 02 '20 at 12:35

2 Answers2

1

rec is a tuple of type Tuple2[Int => Int,Int].

in your statement val y : rec = (f:Int => Int, x:Int) => if (x > 0) y( f, 1) else 1, you are trying to call a apply function on the tuple y (y(f,1)). Since the tuple doesnt have a apply function defined you are getting the error rec does not take parameters

as per your sample code your type rec (Int => Int, Int) => Int.

so the code sample would be

type rec = (Int => Int, Int) => Int
val f = (x : Int) => x + x
val y : rec = (f:Int => Int, x:Int) => if (x > 0) y( f, 1) else 1
rogue-one
  • 11,259
  • 7
  • 53
  • 75
0

Check This link for this answer explanation

var sumIt:(Int => Int) = (x: Int) => {if(x<=1) 1 else sumIt(x-1)+x
  • You could also directly flag the question as duplicated. Thanks anyway for the hint. – dboy May 02 '20 at 12:36
  • 1
    @dboy They can't. [Flag posts](https://stackoverflow.com/help/privileges/flag-posts) requires 15 reputation points :) – Scratte May 02 '20 at 13:22