Scala rekurencja

0
def sum(f: Int => Int)(a: Int, b: Int): Int = {
def loop(a: Int, acc: Int): Int = {
if (???) ???
else loop(???, ???)
}
loop(???, ???)
} 
3

Gotowiec:

import scala.annotation.tailrec

object Main {
  def sum(f: Int => Int)(a: Int, b: Int): Int = {
    @tailrec
    def loop(x: Int, acc: Int): Int = {
      if (x > b) {
        acc
      } else {
        loop(x + 1, acc + f(x))
      }
    }
    loop(a, 0)
  }

  def main(args: Array[String]) {
    println(sum((x: Int) => x * x)(3, 5))
  }
}

1 użytkowników online, w tym zalogowanych: 0, gości: 1