Skip to content

Instantly share code, notes, and snippets.

@radustoenescu
Last active August 29, 2015 13:58
Show Gist options
  • Save radustoenescu/10360919 to your computer and use it in GitHub Desktop.
Save radustoenescu/10360919 to your computer and use it in GitHub Desktop.
Lab of infinite lists in scheme
; delay construct
(define doi (delay (+ 1 1)))
; force a delay to compute its result
(force doi)
; cons for streams
(define-syntax conss
(syntax-rules ()
((conss x y)
(cons x (delay y)))))
; car
(define cars car)
; cdr
(define (cdrs stream) (force (cdr stream)))
; null?
(define nulls? null?)
; empty
(define emptys '())
; take
(define (takes n s)
(if (zero? n)
emptys
(cons (cars s) (takes (- n 1) (cdrs s)))))
; infinite steam of ones
(define ones (conss 1 ones))
(takes 10 ones)
; stream of natural numbers
(define naturals
(letrec
(
(next-element (lambda (n) (+ n 1)))
(step (lambda (n) (conss n (step (next-element n)))))
)
(step 0)
)
)
(takes 10 naturals)
(define (is-prime? n)
(define (is-prime-helper? n d)
(if (> d (quotient n 2))
#t
(if (zero? (remainder n d))
#f
(is-prime-helper? n (+ d 1)))))
(is-prime-helper? n 2))
(is-prime? 2)
(is-prime? 7)
(is-prime? 8)
(define (next-element n)
(if (is-prime? (+ n 1))
(+ n 1)
(next-element (+ n 1))))
(next-element 7)
(next-element 23)
; stream of primes
(define primes
(letrec
(
(step (lambda (n) (conss n (step (next-element n)))))
)
(step 2)
)
)
(takes 20 primes)
; create the stream of pairwise element sums
(define (zipsum s1 s2)
(conss (+ (cars s1) (cars s2)) (zipsum (cdrs s1) (cdrs s2))))
; stream of even numbers
(define even (zipsum naturals naturals))
(takes 10 even)
; stream of fibonacci numbers
(define fibo
(conss 0 (conss 1 (zipsum fibo (cdrs fibo)))))
(takes 20 fibo)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment