Created
May 12, 2016 11:39
-
-
Save bcc32/c5437fa078ecf7910c4e6b0628821a25 to your computer and use it in GitHub Desktop.
The classic Haskell example in Scheme
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
(define-syntax stream-cons | |
(syntax-rules () | |
((_ h t) | |
(cons h (delay t))))) | |
(define stream-car car) | |
(define (stream-cdr stream) | |
(force (cdr stream))) | |
(define stream-nil '()) | |
(define stream-null? null?) | |
(define (stream-ref s i) | |
(if (zero? i) | |
(stream-car s) | |
(stream-ref (stream-cdr s) (- i 1)))) | |
(define (stake s i) | |
(if (zero? i) | |
'() | |
(cons (stream-car s) (stake (stream-cdr s) (- i 1))))) | |
(define (smap f stream) | |
(if (stream-null? stream) | |
stream-nil | |
(stream-cons (f (stream-car stream)) | |
(smap f (stream-cdr stream))))) | |
(define (sfilter pred stream) | |
(cond | |
((stream-null? stream) stream-nil) | |
((pred (stream-car stream)) (stream-cons (stream-car stream) | |
(sfilter pred (stream-cdr stream)))) | |
(else (sfilter pred (stream-cdr stream))))) | |
(define (zip-with f s1 s2) | |
(cond | |
((null? s1) stream-nil) | |
((null? s2) stream-nil) | |
(else (stream-cons (f (stream-car s1) (stream-car s2)) | |
(zip-with f (stream-cdr s1) (scdr s2)))))) | |
(define fibs | |
(stream-cons 1 | |
(stream-cons 1 | |
(zip-with + fibs (stream-cdr fibs))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment