I'm currently learning Scala and have struggled with using placeholder syntax on zip
ped collections. For example, I want to filter the zipped array from items where l2[i] >= l1[i]. How can I do this using an explicit function literal or the placeholder syntax? I have tried:
scala> val l = List(3, 0, 5) zip List(1, 2, 3)
l: List[(Int, Int)] = List((3,1), (4,2), (5,3))
scala> l.filter((x, y) => x > y)
<console>:9: error: missing parameter type
Note: The expected type requires a one-argument function accepting a 2-Tuple.
Consider a pattern matching anonymous function, `{ case (x, y) => ... }`
l.filter((x, y) => x > y)
^
<console>:9: error: missing parameter type
l.filter((x, y) => x > y)
scala> l.filter((x:Int, y:Int) => x > y)
<console>:9: error: type mismatch;
found : (Int, Int) => Boolean
required: ((Int, Int)) => Boolean
l.filter((x:Int, y:Int) => x > y)
Trying the placeholder syntax:
scala> l.filter(_ > _)
<console>:9: error: missing parameter type for expanded function ((x$1, x$2) => x$1.$greater(x$2))
Note: The expected type requires a one-argument function accepting a 2-Tuple.
Consider a pattern matching anonymous function, `{ case (x$1, x$2) => ... }`
l.filter(_ > _)
^
<console>:9: error: missing parameter type for expanded function ((x$1: <error>, x$2) => x$1.$greater(x$2))
l.filter(_ > _)
So it seems to require a function on a Pair
:
scala> l.filter(_._1 > _._2)
<console>:9: error: missing parameter type for expanded function ((x$1, x$2) => x$1._1.$greater(x$2._2))
Note: The expected type requires a one-argument function accepting a 2-Tuple.
Consider a pattern matching anonymous function, `{ case (x$1, x$2) => ... }`
l.filter(_._1 > _._2)
^
<console>:9: error: missing parameter type for expanded function ((x$1: <error>, x$2) => x$1._1.$greater(x$2._2))
l.filter(_._1 > _._2)
So what am I doing wrong? Is match
way the only one? Thanks for the help.
As you found out
filter
overList
requires a function with just one parameter (in your case aTupple2
aka "Pair"):And this
(x, y) => x > y
means a function with two parameters(A, B) => Boolean
. So you went in the right direction in using_1
and_2
, but each use of_
represents a new parameter so_._1 > _._2
is actually equivalent to(x, y) => x._1 > y._2
. Thus if you want to use the same argument more than once you cannot use underscore:Another possibility is to use pattern matching to expand the
Tupple2
:Alternatively, you can use
zipped
which will return aTuple2Zipped
and its filter accepts a function with two parameters (simplified signature below):You can use the
zipped
this way:The
filter
ofTuple2Zipped
returns a pair of lists instead of a list of pairs, so to convert to the second form you can use.zipped.toList
.