Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concise syntax for function composition in Scala?

I'm learning Scala and ran across the following task - if string is blank then return null, otherwise uppercase it.

There are two functions in Apache Commons that composed together solves the problem. In Haskell I'd just write:

upperCaseOrNull = StringUtils.stripToNull . StringUtils.upperCase

However I can't find a way to do an easy and clean function composition in Scala. the shortest way I found is as follows:

def upperCaseOrNull (string:String) = StringUtils.stripToNull (StringUtils.upperCase(string))
def upperCaseOrNull = StringUtils.stripToNull _ compose StringUtils.upperCase _

Does Scala offer a more concise syntax, possibly without all those underscores?

like image 214
piotrek Avatar asked Mar 14 '14 15:03

piotrek


1 Answers

Haskell is a master of extreme compactness for a few things it really cares about. So it's pretty much impossible to beat. If you are doing so much function composition that the overhead really gets in your way (personally, I'd be a lot more troubled by repeating StringUtils.!), you can do something like

implicit class JoinFunctionsCompactly[B,C](g: B => C) {
  def o[A](f: A => B) = g compose f
}

so now you only have four extra characters (_ twice) over Haskell.

like image 193
Rex Kerr Avatar answered Sep 29 '22 13:09

Rex Kerr