Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operators as function literals

Tags:

scala

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.

like image 302
Dave Griffith Avatar asked Sep 27 '13 14:09

Dave Griffith


People also ask

What are the 6 types of literals?

Primitive data types include int, byte, short, float, boolean, double, and char, whereas non-primitive data types include arrays, string, and classes. The primitive literals in java int, byte, short, float, boolean, double, and char represent certain signed integer values.

What are literals give 2 examples?

Literals are the constant values assigned to the constant variables. We can say that the literals represent the fixed values that cannot be modified. It also contains memory but does not have references as variables. For example, const int =10; is a constant integer expression in which 10 is an integer literal.

What are literals C++?

C++ Literals. Literals are data used for representing fixed values. They can be used directly in the code. For example: 1 , 2.5 , 'c' etc. Here, 1 , 2.5 and 'c' are literals.

What is string literal operator?

A string literal or anonymous string is a string value in the source code of a computer program. Modern programming languages commonly use a quoted sequence of characters, formally "bracketed delimiters", as in x = "foo" , where "foo" is a string literal with value foo .


1 Answers

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" -> (_/_)) 
like image 74
maasg Avatar answered Sep 28 '22 03:09

maasg