wheel-utils/example.scm

63 lines
1.9 KiB
Scheme
Raw Normal View History

2020-06-04 14:41:57 +02:00
(use-modules (srfi srfi-1)
(wheel-utils wheel))
;;; Example: fizzbuzz.
;; First we generate out sub-proto-wheels.
(define fizz (every-n-in "fizz" 3))
(define buzz (every-n-in "buzz" 5))
;; Then we merge our proto-wheels
(define proto-wheel (generate-wheel
(lambda x
(let ((l (filter values x)))
(if (null? l)
#f
(apply string-append l))))
fizz
buzz))
;; Then we make our wheel circular so that we don't have to check any null.
(define actual-wheel (apply circular-list proto-wheel))
(define (wheel-fizzbuzz n)
(let loop ((i 1) (wheel actual-wheel))
(if (> i n)
'()
(cons (or (car wheel) i) (loop (+ i 1) (cdr wheel))))))
(define (regular-fizzbuzz n)
(let loop ((i 1))
(cond
((> i n) '())
((eq? 0 (euclidean-remainder i 15))
(cons "fizzbuzz" (loop (+ i 1))))
((eq? 0 (euclidean-remainder i 3))
(cons "fizz" (loop (+ i 1))))
((eq? 0 (euclidean-remainder i 5))
(cons "buzz" (loop (+ i 1))))
(else
(cons i (loop (+ i 1)))))))
2020-12-09 21:21:56 +01:00
;;; Example: prime wheel
;; Here we create a skip wheel that we can use to skip multiples of 2 3 5 and 7.
;; It can be used when implementing, say, the sieve of erathostenes to skip numbers
;; that are already known to be divisors of primes. Removing the first 4 prime-multiples
;; drastically reduces the work that the program needs to do. The first false-positive
;; given by the prime wheel is 11² (121), making this an extremely efficient way to
;; reduce work when trying to find primes.
(define prime-wheel
(apply circular-list
(skip-wheel
(every-n-in 2)
(every-n-in 3)
(every-n-in 5)
(every-n-in 7))))
(display prime-wheel)
(cons* 2 3 5 7 (let loop ((n 11) (wheel (drop prime-wheel 1)))
(if (> n 200)
'()
(cons n (loop (+ n (car wheel)) (cdr wheel))))))