Scala传入整数比较器来运行

时间:2014-08-27 00:52:14

标签: scala

def readf(value_name: String, operator:operand, compared_value:Int  f:()=>Unit) {

我想基于传入的value_name字符串在HashMap中查找Int。获取该值我想比较它

value operator comparison_value

如果该陈述为真,我想执行f。

如何传入比较器并评估此逻辑?最好不要写自己的课程。

2 个答案:

答案 0 :(得分:0)

HashMap的结果可以作为一个选项,然后您可以使用operand / comparative_value进行过滤。那么它应该只是结果选项上的一个地图。它看起来像是:

yourMap.get(value_name).filter(_ operator compared_value).map(f)

这确实假设运算符是(Int,Int)=>评论中提到的布尔值

答案 1 :(得分:0)

您的问题所涉及的编辑问题很难帮助,但我会尝试。假设您的范围myMap: Map[String, Int](您的问题未显示)并假设您的运算符确实属于(Int, Int) => Boolean类型,则可以执行以下操作:

scala> val myMap = Map("test" -> 8)
myMap: scala.collection.immutable.Map[String,Int] = Map(test -> 8)

scala> :paste
// Entering paste mode (ctrl-D to finish)

def readf(value_name: String, operator: (Int, Int) => Boolean, compared_value:Int, f:()=>Unit) {
   myMap.get(value_name).filter(operator(_, compared_value)).foreach(_ => f())
}

// Exiting paste mode, now interpreting.

readf: (value_name: String, operator: Int => (Int => Boolean), compared_value: Int, f: () => Unit)Unit

scala> val eqComparator = ((_: Int) == (_: Int))
eqComparator: (Int, Int) => Boolean = <function2>

scala> val f = () => println("success")
f: () => Unit = <function0>

scala> readf("test", eqComparator, 8, f)
success

scala> readf("test", eqComparator, 5, f)

scala> readf("other", eqComparator, 8, f)

(编辑删除咖喱经营者。这可能更加清晰。)