Peter Thomas
Peter Thomas

Reputation: 58128

Concise notation for single arg anonymous function (avoiding underscore) not working as expected

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[Int], 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?

Upvotes: 3

Views: 849

Answers (3)

Lutz
Lutz

Reputation: 4745

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).

Upvotes: 1

incrop
incrop

Reputation: 2738

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.

Upvotes: 10

Nate Nystrom
Nate Nystrom

Reputation: 475

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.

Upvotes: 3

Related Questions