所以我根据我所读到的内容,我已经得到了这种形式:
def arithmetic_iter(op: (Int, Int) => Int, f: Int => Int, base: Int)(a: Int, b: Int): Int = {
def iter(a: Int, base: Int): Int =
if (a > b) base
else iter(a + 1, op(base, f(a)))
iter(a, base)
}
但是,我想做这样的事情:
def route(m:Message) = {
(e: Endpoint) => e.send(m)
}
使用上述功能。所以我想出了这个数字:
def arithmetic_iter_lambda(op: (Int, Int) => Int, f: Int => Int, base: Int)(a: Int, b: Int): Int = {
(a: Int, b: Int) =>
Int = {
def iter(a: Int, base: Int): Int =
if (a > b) base
else iter(a + 1, op(base, f(a)))
iter(a, base)
}
}
不幸的是,我收到一条错误消息:重新分配给val。
所以我坚持如何修复arithmetic_iter_lambda。
答案 0 :(得分:2)
首先,要修复arithmetic_iter_lambda,请尝试:
def arithmetic_iter_lambda(op: (Int, Int) => Int,
f: Int => Int,
base: Int): (Int, Int) => Int = {
(a: Int, b: Int) => {
def iter(a: Int, base: Int): Int =
if (a > b) base
else iter(a + 1, op(base, f(a)))
iter(a, base)
}
}
(请注意,我已将函数的参数切换为单独的行,只是为了让行停止运行太久)。
其次,给定您的初始arithmetic_iter函数,您可以通过以下方式获得相同的效果:
def alt_arithmetic_iter_lambda(
op: (Int, Int) => Int,
f: Int => Int,
base: Int): (Int, Int) => Int = arithmetic_iter(op, f, base) _
(同样,可能都在一条线上,但它会很长)。