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@(irb):3>>
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
···
On Fri, 18 Apr 2008 06:35:08 +0900 Stedwick <philip.brocoum@gmail.com> wrote:
I have seen many tutorials on the Internet explaining where lambdas
CAN be used, such as clever multiplication functions, but when are
they actually NEEDED?
Sure, I can take a lambda and "pass it around" so to speak, but I can
call a function from anywhere too, right?
Can somebody give me an extremely useful, NOT complicated, example of
when lambdas are the absolute perfect solution to a problem?
Thanks!
--
Akimichi Tatsukawa