2

私は現在 Scala を学んでおり、zipped コレクションでプレースホルダー構文を使用するのに苦労しています。たとえば、l2[i] >= l1[i] のアイテムから圧縮配列をフィルター処理したいとします。明示的な関数リテラルまたはプレースホルダー構文を使用してこれを行うにはどうすればよいですか? 私が試してみました:

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)

プレースホルダー構文を試す:

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(_ > _)

したがって、次の関数が必要なようです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)

それで、私は何を間違っていますか?方法はmatch唯一のものですか?助けてくれてありがとう。

4

2 に答える 2

5

これを使って:

l.filter { case (x, y) => x > y }

また

l.filter(x => x._1 > x._2)

また、Scala では、型情報は関数の本体からその引数に流れません。

于 2015-08-10T23:33:03.850 に答える