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 | |
(define (grains) | |
(letrec | |
([f | |
(lambda (n) | |
(cons n | |
(lambda () (f (* 2 n)) )))]) | |
(f 1))) | |
(define (stream-for-n-steps stream n) | |
(letrec ([f | |
(lambda(i stream-rest) | |
(if (= i 0) | |
empty | |
(cons (car (stream-rest)) | |
(f (- i 1) (cdr (stream-rest))))))]) | |
(f n stream))) | |
(define (square sqr-num) | |
(last (stream-for-n-steps grains sqr-num))) | |
(define total-grains | |
(lambda () | |
(foldr + 0 (stream-for-n-steps grains 64)))) |
The stream is the function grains which returns a pair containing the first value and the generator of the rest of the stream.
The stream-for-n-steps helper gets n values from the stream.
Probably there is a function to do this directly in Racket but I wanted to remember what we did in the Coursera Programming Languages course.
Now I want to do something similar in Clojure.
No comments:
Post a Comment