...">

Math Currying Operators in Scala

I want to create a simple map from mathematical operators for the corresponding functions:

var ops = Map("+" -> +, "-" -> -) 

How to do it in Scala?

+7
source share
2 answers
 val ops = Map("+" -> ((_: Int) + (_: Int)), "-" -> ((_: Int) - (_:Int))) 

or

 val ops = Map[String, (Int, Int) => Int]("+" -> (_+_), "-" -> (_-_)) 

or even, for actual currying,

 val ops = Map("+" -> ((_: Int) + (_: Int)).curried, "-" -> ((_: Int) - (_:Int)).curried) 

These functions are bound to Int . Well, Scala is not a point programming language, it is object-oriented, and one in which there is no superclass common to all numeric types. In any case, if you object to this, then you have a completely different problem, which I was asked and talked about many times over the stack overflow (in fact, this was my first question Scala, iirc).

+6
source

If you want functions to execute in curry, then this is most likely the shortest way to do this.

 scala> val ops: Map[String, Int => Int => Int] = Map( | "+" -> (x => y => x + y), | "-" -> (x => y => x - y) | ) ops: Map[String,Int => Int => Int] = Map(+ -> <function1>, - -> <function1>) 

However, this card is limited only to Int s. If you need general operations, you will need to use the Numeric binding.

 scala> def ops[N : Numeric]: Map[String, N => N => N] = { | import Numeric.Implicits._ | Map( | "+" -> (x => y => x + y), | "-" -> (x => y => x - y) | ) | } ops: [N](implicit evidence$1: Numeric[N])Map[String,N => N => N] 

The main caveat with this approach is that a map is created every time you call ops .

+11
source

All Articles