Skip to content

Instantly share code, notes, and snippets.

@zonggen
Last active October 26, 2018 00:38
Show Gist options
  • Save zonggen/8c2bde6c8d0c83c3cbced57088286aa6 to your computer and use it in GitHub Desktop.
Save zonggen/8c2bde6c8d0c83c3cbced57088286aa6 to your computer and use it in GitHub Desktop.
Represent natural number as a stream using lazy evaluation property
#lang racket
;; natural number representation as a stream using lazy evaluation property
(define natural-number
(letrec
([nat-stream
(lambda (i)
(cons (thunk i) (thunk (nat-stream (+ i 1)))))])
(nat-stream 0)))
;; return the first n elements of the stream as a list
(define (first-n n stream)
(if (equal? n 0)
null
(cons ((car stream))
(first-n (- n 1) ((cdr stream))))))
;; return the first 10 natural number
(first-n 10 natural-number)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment