我想把一个表达式,比如:a.meth(b),转换成一个(A, B) => C类型的函数来执行精确的计算。
我到目前为止最好的尝试是这样的:
def polish[A, B, C](symb: String): (A, B) => C = { (a, b) =>
// reflectively check if "symb" is a method defined on a
// if so, reflectively call symb, passing b
}然后像这样使用它:
def flip[A, B, C](f : (A, B) => C): (B, A) => C = {(b, a) => f(a,b)}
val op = flip(polish("::"))
def reverse[A](l: List[A]): List[A] = l reduceLeft op正如你所看到的,它相当丑陋,你必须“手动”做很多类型检查。
有没有别的选择?
发布于 2014-08-20 20:38:37
您可以使用普通旧子类型多态性轻松地实现这一点。只需声明接口
trait Iface[B, C] {
def meth(b: B): C
}然后,您就可以轻松地实现polish了
def polish[B, C](f: (Iface[B, C], B) => C): (Iface[B, C], B) => C = { (a, b) =>
f(a, b)
}使用它是完全类型安全的
object IfaceImpl extends Iface[String, String] {
override def meth(b: String): String = b.reverse
}
polish((a: Iface[String, String], b: String) => a meth b)(IfaceImpl, "hello")更新:
实际上,您可以只使用闭包来实现这一点
def polish[A, B, C](f: (A, B) => C): (A, B) => C = f
class Foo {
def meth(b: String): String = b.reverse
}
polish((_: Foo) meth (_: String))(new Foo, "hello")或者根本不使用helper函数:)
val polish = identity _ // Magic at work
((_: Foo) meth (_: String))(new Foo, "hello")https://stackoverflow.com/questions/25401390
复制相似问题