Scala ひと巡り : 関数のネスト (Nested Functions)

Scala では、関数定義をネストできます。次のオブジェクトは、整数のリストから閾値未満の値を抽出する、filter 関数を提供します:

object FilterTest extends Application { def filter(xs: List[Int], threshold: Int) = { def process(ys: List[Int]): List[Int] = if (ys.isEmpty) ys else if (ys.head < threshold) ys.head :: process(ys.tail) else process(ys.tail) process(xs) } println(filter(List(1, 9, 2, 8, 3, 7, 4), 5)) }

ネストされた関数 process が、filter のパラメータ値である外側のスコープ中で定義された変数 threshold を参照することに注意してください。

次はこのプログラムの出力です:

List(1,2,3,4)