0

因此,根据我所读到的内容,我得到了这种形式的currying:

  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。

所以我坚持如何修复算术_iter_lambda。

4

1 回答 1

2

首先,要修复算术_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)
      }
  }

(请注意,我已将函数的参数分割成单独的行,只是为了阻止行运行时间过长)。

其次,给定您的初始算术_iter 函数,您可以通过以下方式获得相同的效果:

def alt_arithmetic_iter_lambda(
    op: (Int, Int) => Int,
    f: Int => Int,
    base: Int): (Int, Int) => Int = arithmetic_iter(op, f, base) _

(同样,可能都在一条线上,但会相当长)。

于 2013-09-23T12:11:29.130 回答