- 45 名前:42 mailto:sage [2012/03/11(日) 08:40:16.04 ]
- >>44のメソッドfoldの定義を更に簡潔にしてみた
def fold(init, xs, &fn); xs.inject(init, &fn); end def sum(ary); fold(0, ary) { |xs, x| xs + x }; end def product(ary); fold(1, ary) { |xs, x| xs * x }; end def reverse(ary); fold([], ary) { |xs, x| xs.unshift(x) }; end def length(ary); fold(0, ary) { |xs, _| xs + 1 }; end
|

|