After going through some examples on the web I realize that there is a way to write an anonymous function without the underscore when only a single arg. Also, I'm experimenting with the "span" method on List, which I never knew existed. Anyway, here is my REPL session:
scala> val nums = List(1, 2, 3, 4, 5)
nums: List[Int] = List(1, 2, 3, 4, 5)
scala> nums span (_ != 3)
res0: (List[Int], List[Int]) = (List(1, 2),List(3, 4, 5))
scala> nums span (3 !=)
res1: (List[In开发者_Python百科t], List[Int]) = (List(1, 2),List(3, 4, 5))
So far so good. But when I try to use the "less than" operator:
scala> nums span (_ < 3)
res2: (List[Int], List[Int]) = (List(1, 2),List(3, 4, 5))
scala> nums span (3 <)
res3: (List[Int], List[Int]) = (List(),List(1, 2, 3, 4, 5))
Why is this behaving differently?
scala> nums span (_ < 3)
res0: (List[Int], List[Int]) = (List(1, 2),List(3, 4, 5))
scala> nums span (3 >)
res1: (List[Int], List[Int]) = (List(1, 2),List(3, 4, 5))
3 <
is a shortcut to 3 < _
, which creates a partially applied function from method call.
It's behaving correctly:
scala> nums span (3 < _)
res4: (List[Int], List[Int]) = (List(),List(1, 2, 3, 4, 5))
The predicate is false for the first element of the list, so the first list returned by span
is empty.
scala> nums span (3 < _)
res0: (List[Int], List[Int]) = (List(),List(1, 2, 3, 4, 5))
// is equivalent to
scala> (nums takeWhile{3 < _}, nums.dropWhile{3 < _})
res1: (List[Int], List[Int]) = (List(),List(1, 2, 3, 4, 5))
where
the predicate is false already for the first element(1) therefore nums.takeWhile{false}
results in the empty list List()
For the second part nothing is dropped because the predicate is false already for the first
element(1) and therefore the nums.dropWhile{false}
is the whole list List(1, 2, 3, 4, 5)
.
精彩评论