Scala: unable to put tuple as function argument

I cannot pass a tuple as a parameter to a method:

scala> val c:Stream[(Int,Int,Int)]= Stream.iterate((1, 0, 1))((a:Int,b:Int,c:Int) => (b,c,a+b)) <console>:11: error: type mismatch; found : (Int, Int, Int) => (Int, Int, Int) required: ((Int, Int, Int)) => (Int, Int, Int) 

thanks.

+5
source share
3 answers

Just like a function letter:

 (x:Int) => x + 1 

is a function of one argument, the following

 (x:Int, y: Int, z: Int) => x + y + z 

is a function of three arguments, not a single argument 3tuple

You can do this work neatly with the case :

 scala> val c: Stream[(Int,Int,Int)] = Stream.iterate((1, 0, 1)){ case (a, b, c) => (b, c, a+b) } c: Stream[(Int, Int, Int)] = Stream((1,0,1), ?) 

An alternative is passing a tuple, but it is really ugly due to all _1 accessories:

 scala> val c:Stream[(Int,Int,Int)] = Stream.iterate((1, 0, 1))( t => (t._2, t._3, t._1 + t._2) ) c: Stream[(Int, Int, Int)] = Stream((1,0,1), ?) 
+9
source

lambda (a:Int,b:Int,c:Int) => (b,c,a+b) is a function that takes three arguments. You want it to take one tuple, so you can write ((a:Int,b:Int,c:Int)) => (b,c,a+b) . But it gives an error!

 error: not a legal formal parameter. Note: Tuples cannot be directly destructured in method or function parameters. Either create a single parameter accepting the Tuple3, or consider a pattern matching anonymous function: `{ case (param1, ..., param3) => ... } (((a:Int,b:Int,c:Int)) => (b,c,a+b)) ^ 

Fortunately, the error offers a solution: { case (a, b, c) => (b, c, a+b) }

+2
source

I assume that the expression (a:Int,b:Int,c:Int) => (b,c,a+b) defines a lambda with three arguments, and you need one expanded argument.

-1
source

All Articles