3

I can understand this:

List("one word", "another word") unzip (_ span (_ != ' '))

But don't get what's happening here below in the span. span takes a predicate and I think the braces can be omitted as span is used inline and has only one parameter but why isn't there any _ and what is ' '.!=

List("one word", "another word") unzip (_ span ' '.!=)
asked Feb 3, 2014 at 22:25

1 Answer 1

4

In Scala, operators are just special-named methods. Here ' '.!= fetches but does not apply the != to the ' ' object. This method takes one parameter and returns a boolean value.

For any function f that takes a single argument, (x => f(x)) and f are equivalent expressions – so there is no need to wrap such a function into another lambda.

The span method takes a predicate, and partitions a sequence (here: String) into a prefix that satisfies the predicate, and a suffix that doesn't. Here we want to get the string up to the first space.

  • In the first line, we use the predicate (_ != ' '), more clearly (c => c != ' ').
  • We can now swap the arguments of the inequality "operator", as this operation should be reflexive. We now have: (c => ' ' != c).
  • We can now use the explicit method call syntax: (c => ' '.!=(c)).
  • Next, we save that method in another variable:

    val f: (Char => Boolean) = ' '.!=
    ...
    (c => f(c))
    
  • As stated above, f and (c => f(c)) are equivalent, therefore (_ != ' ') and ' '.!= must be equivalent too.

answered Feb 3, 2014 at 22:48
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.