我正在尝试实现一个由函数 g
和 f
组成的函数,即 g.f
。理想情况下,我希望 f 接受可变数量的参数,以便以下代码有效:
def add (x: Int, y: Int) : Int = x + y
def addOne (x: Int) : Int = x + 1
def sq (x : Int) : Int = x * x
def compose[A, B, C] (g : B => C, f: A => B, args : A) : C = g(f(args))
assert(compose(sq, addOne, 5) == 36)
// this doesn't work yet
def compose_ideal[A, B, C] (g : B => C, f: (A*) => B, args : A*) : C = g(f(args))
assert(compose_ideal(sq, addOne, 5) == 36)
assert(compose_ideal(sq, add, 3, 7) == 100)
我收到 compose_ideal
的以下错误:
error: repeated parameters are only allowed in method signatures; use Seq instead
def compose_ideal[A, B, C] (g : B => C, f: (A*) => B, args : A*) : C = g(f(args))
我想在函数签名中说的是,f 是一个函数,它采用可变数量的 A 类型参数,如 args: A*
所示。但是,由于类型不匹配,def compose_ideal[A, B, C] (g : B => C, f: Seq[A] => B, args : A*) : C = g(f(args : _*))
之类的东西也不起作用。
我该如何解决这个错误?