fib.rb

candlerb (Brian Candler), 11/03/2008 06:41 pm

Download (676 Bytes)

 
1
class Enumerator
2
  def lazy_map(&blk) 
3
    Enumerator.new do |y|
4
      each do |e|
5
        y << blk[e]
6
      end
7
    end
8
  end
9

    
10
  def lazy_select(&blk)
11
    Enumerator.new do |y|
12
      each do |e|
13
        y << e if blk[e]
14
      end
15
    end
16
  end
17
end
18

    
19
class Fib
20
  def initialize(a=1,b=1)
21
    @a, @b = a, b
22
  end
23
  def each
24
    a, b = @a, @b
25
    yield a
26
    while true
27
      yield b
28
      a, b = b, a+b
29
    end
30
  end
31
end
32

    
33
Fib.new.to_enum.                                      # generator
34
  lazy_select { |x| x % 2 == 0 }.                     # filter
35
  lazy_map { |x| "<#{x}>" }.                          # filter
36
  each_with_index { |x,c| puts x; break if c >= 20 }  # consumer