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 ' '.!=)
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.