我对 scala 很陌生,所以你可以原谅我这个基本的新手问题。我有以下代码片段。
type Pred[A, B] = (A, B) => Int;
def abs[A, B](p: (A, B) => Int): (A, B) => Int =
(a, b) => if (p(a, b) < 0) -(p(a, b)) else (p(a, b));
def multiply(a: Int, b: Int): Int =
a * b;
def subtract(a: Int, b: Int): Int =
a - b;
val absMultiply = abs(multiply);
val absSubstract = abs(subtract);
println("abs(10 * 10) = " + absMultiply.apply(10, 10));
println("abs(10 - 100) = " + absSubstract.apply(10, 100));
因此,正如我正确理解的那样,应该可以将 (A,B) => Int 替换为 Pred[A, B]。
def abs[A, B](p: Pred[A, B]): Pred[A, B] =
(a, b) => if (p(a, b) < 0) -(p(a, b)) else (p(a, b));
但后来我得到一个编译器异常
type mismatch; found : (Int, Int) => Int required: (A, B) => Int
type mismatch; found : (Int, Int) => Int required: (A, B) => Int
我误解这里有什么问题吗?
非常感谢您的帮助。
西里尔