Last active
October 26, 2018 00:38
-
-
Save zonggen/8c2bde6c8d0c83c3cbced57088286aa6 to your computer and use it in GitHub Desktop.
Represent natural number as a stream using lazy evaluation property
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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