P.211 ~ 212 の部分再帰関数の実装。名前づけで混乱したので整理しなおしてみた。
# 部品1
def zero
0
end
# 部品2
def increment(n)
n + 1
end
# 部品3
def recurse(f, g, *args)
*xs, y = args
if y.zero?
send(f, *xs)
else
args_updated = xs + [y-1] # args の末尾の値をひとつ減じたリスト
accumulated = recurse(f, g, *args_updated)
send(g, *args_updated, accumulated)
end
end
そして
def add(x, y)
def base(x)
puts x
x
end
def rec(x, y, acc)
puts "#{x}; #{y}; #{acc}"
increment(acc)
end
recurse(:base, :rec, x, y)
end
add(increment(increment(zero)), increment(increment(increment(zero))))
これを実行すると
2 2; 0; 2 2; 1; 3 2; 2; 4
がプリントされ、結果 5
が得られる。