On Fri, 18 Apr 2008 06:35:08 +0900
Stedwick [email protected] wrote:
Thanks!
How about using lambda as representing recursive type and
implemeting lazy evaluation in easygoing way.
class Natural
def initialize
@succ = lambda {Natural.new}
end
def take(maximum)
[1] + if maximum == 1
[]
else
@succ.call.take(maximum - 1)
end
end
def accumulate(num, result = 0)
if num == 0
result
else
accumulate(num - 1, result + 1)
end
end
def summate(maximum)
if maximum == 1
1
else
accumulate(maximum) + summate(maximum - 1)
end
end
def filter(index = 1,result = [], &block)
num = accumulate(index)
if yield(num) == true
result << num
filter(index + 1,result, &block)
else
result
end
end
end
irb(main):040:0> n = Natural.new
#<Natural:0xb7a970ec @succ=#Proc:0xb7a9c2a4@:3(irb)>
irb(main):041:0> n.take(100)
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1]
irb(main):042:0> n.accumulate(100)
100
irb(main):043:0> n.filter {|i| i < 10}
[1, 2, 3, 4, 5, 6, 7, 8, 9]
irb(main):045:0> n.summate(100)
5050