Monday, May 14, 2007

Generator

Languages like Python, Ruby provide a keyword `yield' to help build a generator. It's really convenient for programmers who hate C-style static local variables, which indicates not thread-safe. For example:

def sequence(start):
  current = start
    while True:
      yield current
      current = current + 1

#Create a new sequence generator starting at 1
generator_func = sequence(1)
print generator_func.next() #prints 1
print generator_func.next() #prints 2
print generator_func.next() #prints 3

Languages support functional programming needn't craft a `yield' keyword (most of them support another more general mechanism named `continuation'). We can easily build a generator like above use Scheme:

; helper procedure to construct a simple generator
(define (make-iter start step)
  (lambda ()
    (let ((old start))
      (begin (set! start (+ start step))
          old))))

; a generator which starts from 1 and steps 1 on each accumulation
(define sequence (make-iter 1 1))

(sequence) ; evaluates 1
(sequence) ; evaluates 2
(sequence) ; evaluates 3

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home