Scala by Example > 演習5.2.1〜5.2.4解答案
Scala by Example > 5.2 カリー化 (Currying)の演習問題の解答案です。
演習 5.2.1
この問題ですが、??を埋めてもコンパイルエラーになって変だなと思ったら、原文とちょっと違ってますね。
原文の問題
def sum(f: Int => Int)(a: Int, b: Int): Int = { def iter(a: Int, result: Int): Int = { if (??) ?? else iter(??, ??) } iter(??, ??) }
原文に沿った解答にしました。
def sum(f: Int => Int)(a: Int, b: Int): Int = { def iter(a: Int, result: Int): Int = { if (a > b) result else iter(a + 1, f(a) + result) } iter(a + 1, f(a)) }
演習 5.2.2
末尾再帰での計算を積に変えただけです。
def product(f: Int => Int)(a: Int, b: Int): Int = { def iter(a: Int, result: Int): Int = { if (a > b) result else iter(a + 1, f(a) * result) } iter(a + 1, f(a)) }
演習 5.2.3
def factorial(n: Int): Int = product(x => x)(1, n)
演習 5.2.4
違いが末尾再帰でのresult反映方法だけなので、その部分を関数引数で指定できるようにしてみました。
def func(f: Int => Int, g: (Int, Int) => Int)(a: Int, b: Int): Int = { def iter(a: Int, result: Int): Int = { if (a > b) result else iter(a + 1, g(f(a), result)) } iter(a + 1, f(a)) }