Ok ok, I have to admit that Racket is pretty cool sometimes 😀 (despite it’s very verbous :D)
This is my solution for the problem 5:
#lang racket (define (div-1-20? x) (let aux ([x x] [acc 1]) (cond [(= 0 x) #f] [(= 21 acc) #t] [(= 0 (modulo x acc)) (aux x (add1 acc))] [else #f]))) ;; Pretty cool (for ([i (stop-after (in-naturals 1) div-1-20?)] #:when (div-1-20? i)) (display i))
The dark magic is provided by in-naturals, stop-after and the #:when clausole:
- in-naturals provide a lazy sequence from start to +inf
- stop-after make sure that for will stop when the predicate div-1-20? will be satisfied
- when assures that only when div-1-20? will be satisfied the for body will be executed
As result this code runs in constant space and is no memory-consuming at all 🙂
Bye!
Alfredo