How to use> << => = as functions?

I need to define some case classes, for example the following:

 case class Gt(key: String, value: Any) extends Expression { def evalute[V, E](f: String => Any) = { def compare(v: Any): Boolean = { v match { case x: Number => x.doubleValue > value.asInstanceOf[Number].doubleValue case x: Array[_] => x.forall(a => compare(a)) case x => x.toString > value.toString } } compare(f(key)) } } 

I do not like to repeat that for> <> = and <=

I also tried this:

 trait Expression { def evalute[V, E](f: String => Any) = true def compare(v: Any, value: Any, cp: (Ordered[_], Ordered[_]) => Boolean): Boolean = { v match { case x: Number => cp(x.doubleValue, value.asInstanceOf[Number].doubleValue) case x: Array[_] => x.forall(a => compare(a, value, cp)) case x => cp(x.toString, value.toString) } } } case class Gt(key: String, value: Any) extends Expression { def evalute[V, E](f: String => Any) = { compare(f(key), value, ((a, b) => a > b)) } } 

but this does not work :(

 error: could not find implicit value for parameter ord: scala.math.Ordering[scala.math.Ordered[_ >: _$1 with _$2]] compare(f(key), value, ((a, b) => a > b)) 

Is there a way that passes an operator as a function in scala?

+6
source share
3 answers

(a, b) => a > b works fine. Your problem is with types.

  • evalute[V, E] assumed that V and E in evalute[V, E] ?

  • You pass it (a, b) => a > b as the parameter cp: (Ordered[_], Ordered[_]) => Boolean . So you have a: Ordered[_] and b: Ordered[_] . This is the same as a: Ordered[X] forSome {type X} and b: Ordered[Y] forSome {type Y} . With these types a > b does not make sense.

+6
source

I am not familiar with Scala, it seems to support anonymous / lambdas functions: http://www.scala-lang.org/node/133

0
source

In Scala, these are not operators, but methods. You can raise any method to a function by placing an underscore under it. eg

 Welcome to Scala version 2.8.0.final (Java HotSpot(TM) Client VM, Java 1.6.0_21). Type in expressions to have them evaluated. Type :help for more information. scala> val f: (Int => Boolean) = 1 <= _ f: (Int) => Boolean = <function1> scala> (0 to 2).map(f) res0: scala.collection.immutable.IndexedSeq[Boolean] = Vector(false, true, true) 
0
source

All Articles