Question

So I according to what I've read I've gotten this form of currying down:

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

However, I wanted to do something like this:

def route(m:Message) = {
  (e: Endpoint) => e.send(m)
}

With the function above. So I came up with this number:

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

Unfortunately, I get an error that says: reassignment to val.

So I'm stuck on how to fix arithmetic_iter_lambda.

Was it helpful?

Solution

First, to fix arithmetic_iter_lambda, try:

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

(Note that I have chopped the arguments to the function into separate lines simply to stop the line running on too long).

Second, given your initial arithmetic_iter function, you can get the same effect via:

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

(Again, could all be on one line, but it would be rather long).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top