generators.scm 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. ;; ================
  2. ;; DATA ABSTRACTION
  3. ;; ================
  4. ;; The value is always the first value of the generator.
  5. (define get-value car)
  6. ;; A generator's producing procedure needs to be applied to get the
  7. ;; next thing.
  8. (define (get-next a-gen)
  9. ((cdr a-gen)))
  10. ;; A generator is only a tuple containing the current value and the
  11. ;; procedure to create the next value
  12. (define (make-gen proc start)
  13. (cons start
  14. (λ ()
  15. (make-gen proc (proc start)))))
  16. (define STOP-SYMBOL 'none)
  17. ;; ========
  18. ;; EXAMPLES
  19. ;; ========
  20. ;; An infinite list of numbers.
  21. (define natural-numbers
  22. (make-gen (λ (x) (+ x 1))
  23. 0))
  24. ;; A limited list of natural numbers.
  25. (define (limited-natural-numbers limit)
  26. (make-gen (λ (x)
  27. (cond [(< x limit) (+ x 1)]
  28. [else STOP-SYMBOL]))
  29. 0))
  30. ;; Print a certain amount of natural numbers.
  31. (define (print-natural-numbers natural-numbers limit)
  32. (let ([current-number (get-value natural-numbers)])
  33. (cond
  34. [(and (symbol? current-number) (eq? current-number STOP-SYMBOL))
  35. (display (simple-format #f "No more numbers available!\n"))]
  36. [(< current-number limit)
  37. (display (simple-format #f "~a\n" current-number))
  38. (print-natural-numbers (get-next natural-numbers) limit)]
  39. [else
  40. (display (simple-format #f "Done.\n"))])))