functional programming - What's the equivalent of Clojure's iterate function in Racket -


i'm playing racket today, , trying produce indefinite sequence of numbers based on multiple applications of same function.

in clojure i'd use iterate function this, i'm not sure equivalent in racket.

in situations can replace use of iterate for/fold.

> (define (mult2 x) (* x 2))  > (for/fold ([x 1])   ; initial value of x 1             ([i 8])   ; count i=0,...,7    (mult2 x))         ; put x = (mult2 x) 256 

the advantage of for/fold can iterate more variables @ time:

(define (mult2 x) (* x 2)) (define (div2 x)  (/ x 2))  (for/fold ([x 1]        ; bind x 1            [y 1])       ; bind y 1           ([i 8])       ; i=0,...,7   (values (mult2 x)     ; put x = (mult2 x)           (div2  y)))   ; put y = (div2 y) 

this return 2 values: 256 , 1/256.

collecting elements easy. here fibonacci example:

(for/fold ([fs '(1)]     ; list of fibonacci numbers generated far            [f1   1]      ; fibonacci number            [f2   1])     ; following fibonacci number           ([i   10])     ; = 0,...,9   (values (cons f2 fs)   ; cons new fibonacci number list fs           f2             ; put f1 = (the old) f2           (+ f1 f2)))    ; put f2 = (the old) f1+f2 

the result consists of 3 values:

'(89 55 34 21 13 8 5 3 2 1 1) 89 144 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -