scalatuples

scala : it is impossible to put a tuple as a function's argument


I can't pass a tuple as a method parameter:

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.


Solution

  • Just as the function literal:

    (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 one argument of a 3tuple

    You can make this work neatly using a case statement:

    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 to pass the tuple, but that's really ugly due to all the _1 accessors:

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