Skip to content

Instantly share code, notes, and snippets.

@judofyr
Created July 29, 2013 15:02
Show Gist options
  • Save judofyr/6104958 to your computer and use it in GitHub Desktop.
Save judofyr/6104958 to your computer and use it in GitHub Desktop.
Lazy lists without closures in Scheme
#lang r5rs
; A lazy list is a cons of two values: a head (a value) and a tail,
; a lambda that returns other lazy list. It's very easy to create a
; closure-based implementation:
(define (lazy-from n)
(cons n (lambda () (lazy-from (+ 1 n)))))
(define (lazy-head lst) (car lst))
(define (lazy-tail lst) ((cdr lst)))
(define nat (lazy-from 0))
; Check that we can print it out nicely
(display (lazy-head nat))
(display (lazy-head (lazy-tail nat)))
; Now, let's accomplish the same without any closures:
(define (elazy-from n)
(let ((code `(,elazy-from ,(+ 1 n))))
(cons n code)))
(define (elazy-head lst) (car lst))
(define (elazy-tail lst) (apply (car (cdr lst)) (cdr (cdr lst))))
; We can use it in the exact same way:
(define enat (elazy-from 0))
(display (elazy-head enat))
(display (elazy-head (elazy-tail enat)))
; And we can define more initializers:
(define (elazy-from-by n inc)
(let ((code `(,elazy-from-by ,(inc n) ,inc)))
(cons n code)))
(define even-numbers (elazy-from-by 0 (lambda (n) (+ 2 n))))
(display (elazy-head (elazy-tail even-numbers)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment