;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: utilities/generators.lisp

;;;; Generators

;;; A generator is a closure that returns the next element of a sequence
;;; each time it is called, so that an infinite sequence can be consumed
;;; one element at a time.

(defun make-powers-of-2 ()
  "Return a generator of the powers of 2: 1, 2, 4, 8, ... [POWERS-OF-2]"
  (let ((i 1))
    #'(lambda ()
	(prog1 i
	  (setf i (* 2 i))))))

(defun generator-take (generator n)
  "The list of the next N elements of GENERATOR."
  (loop repeat n collect (funcall generator)))
