Dave Griffith
Dave Griffith

Reputation: 20515

Operators as function literals

So for a very small formula interpretter someone asked me to code-golf, I wanted to do something like

  val ops = Map("plus" -> + , "minus"-> -, "times"-> *, "div" -> / )

to allow quick conversion between keywords and the functions they describe. Not only did this syntax not parse, but none of the other shorthand syntaxes I tried ( _ + _, _:Int.+_)parsed. Is there a way of doing this as a function shorthand, or am I doomed to writing out the lambdas fully, ruining my golf score.

Edit: The problem in question was integers only. I understand that overloading would make this vastly more difficult otherwise.

Upvotes: 8

Views: 179

Answers (1)

maasg
maasg

Reputation: 37435

Not sure how your score is impacted by defining an additional function. You could lift the operators, using something like this:

def lift(f:(Int,Int)=>Int) = f
val ops = Map("plus" -> lift(_+_), "minus" -> lift(_-_), "times"-> lift(_*_), "div" -> lift(_/_))

And if you want to shave some chars:

def  ↑(f:(Int,Int)=>Int) = f
val ops = Map("plus" -> ↑(_+_), "minus" -> ↑(_-_), "times"-> ↑(_*_), "div" -> ↑(_/_))

And as om-nom-nom comments, this explicit lifting can be done by the compiler as well by providing the type signature to coerse the lifting:

val ops: Map[String, (Int,Int) => Int] = Map("plus" -> (_+_), "minus" -> (_-_), "times"->(_*_), "div" -> (_/_)) 

Upvotes: 5

Related Questions