Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

I need define some case classes like the following one:

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 don't like 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 that not working :(

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 pass a operator as a function in scala?

like image 880
spacedragon Avatar asked Oct 29 '10 03:10

spacedragon


People also ask

How do you use less than or equal to in if formula?

The IF function checks to see if its first argument is true or false and returns the second argument if true and the third if false. For example, =IF(B2<=5, C2, D2) will populate a cell with the value in cell B3 if the value in B2 is less than or equal to five and otherwise will populate it with the value in cell D2.

How do you write greater than or equal to if a function?

The operator (>=) returns TRUE if the first value is greater than or equal to the second value. If not, Excel returns with FALSE. For example, the formula =A1>=COUNT(B2:B10) gets TRUE if the value in cell A1 is greater than or equal to the count of values in the range B2:B10.

What does <= in Excel mean?

'Less Than or Equal to' operator (<=) is one of the six logical operators (also known as the comparison operators) used in Microsoft Excel to compare values. The “<=” operator checks if the first value is less than or equal to the second value and returns 'TRUE' if the answer is yes or else 'FALSE'.


1 Answers

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

  1. What are V and E in evalute[V, E] supposed to be?

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

like image 105
Alexey Romanov Avatar answered Oct 21 '22 11:10

Alexey Romanov