3

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?

2
  • 3
    The (3 <) syntax is transformed into a function through eta expansion. It isn't a topic much discussed on S.O., that I can recall. You could always search about it, and, if you don't find anything, ask someone to explain. Commented Jul 6, 2011 at 17:19
  • @Daniel - thanks, that term was useful for searching, and I found this link Commented Jul 8, 2011 at 12:16

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Now I realized my thinking was upside-down for a while. Accepting this answer, I really needed that explanation on the last line. if you can point me to some reference documentation explaining that particular syntax, that would be great ! Thanks.
Check out args.foreach(println) example at Step 7 of this tutorial
3

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.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.