g85*_*588 2 functional-programming scala function-literal pattern-matching
我目前正在学习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)
Run Code Online (Sandbox Code Playgroud)
尝试占位符语法:
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(_ > _)
Run Code Online (Sandbox Code Playgroud)
所以它似乎需要一个函数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)
Run Code Online (Sandbox Code Playgroud)
那么我做错了什么?是match唯一一个吗?谢谢您的帮助.
用这个:
l.filter { case (x, y) => x > y }
Run Code Online (Sandbox Code Playgroud)
要么
l.filter(x => x._1 > x._2)
Run Code Online (Sandbox Code Playgroud)
同样在Scala中,类型信息不会从函数体传递到其参数.