【激突】関数型言語 VS オブジェクト指向言語
■ このスレッドは過去ログ倉庫に格納されています
004442
2012/03/11(日) 08:35:50.94def fold(init, xs, &fn)
if xs.empty?
init
else
result = fn.call(init, xs[0])
for x in xs[1..(xs.length - 1)]
result = fn.call(result, x, &fn)
end
result
end
end
def sum(ary); fold(0, ary) { |s, x| s + x }; end
def product(ary); fold(1, ary) { |p, x| p * x }; end
def reverse(ary); fold([], ary) { |xs, x| xs.unshift(x) }; end
def length(ary); fold(0, ary) { |n, _| n + 1 }; end
■ このスレッドは過去ログ倉庫に格納されています