2

我想将诸如:的表达式转换为执行该精确计算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

正如您几乎可以看到的,它非常难看,您必须“手动”进行大量类型检查。

有替代方案吗?

4

1 回答 1

0

您可以使用普通的旧子类型多态性轻松实现它。只需声明接口

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")

或者根本没有辅助功能:)

val polish = identity _ // Magic at work

((_: Foo) meth (_: String))(new Foo, "hello")
于 2014-08-20T12:38:36.907 回答