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

6
  • 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. Commented May 23, 2017 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? Commented May 23, 2017 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 Commented May 23, 2017 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 Commented May 23, 2017 at 14:53
  • updated my answer that corrects your type rec definition Commented May 23, 2017 at 14:56

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

0

Check This link for this answer explanation

var sumIt:(Int => Int) = (x: Int) => {if(x<=1) 1 else sumIt(x-1)+x

2 Comments

You could also directly flag the question as duplicated. Thanks anyway for the hint.
@dboy They can't. Flag posts requires 15 reputation points :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.