(define (number-interval f t)
(if (<= f t) (cons f (number-interval (+ f 1) t)) '()))
(define (fb n)
(cond
((eq? (remainder n 15) 0) 'FizzBuzz)
((eq? (remainder n 5) 0) 'Buzz)
((eq? (remainder n 3) 0) 'Fizz)
(else n)
)
)
(define (FizzBuzz m n) (map fb (number-interval m n)))
Then, inspired by Reg's "overthought" Ruby version, I did a Scheme version of his implementation:
(define (carbonate n name)
(lambda (x)
(if (and (number? x) (eq? (remainder x n) 0))
name
x
)
)
)
(define (compose . fns)
(define (compose-list functions)
(if (null? functions)
(lambda (x) x) ; identity function
(lambda (x)
(define (g y) ((compose-list (cdr functions)) y))
(g ((car functions) x))
)
)
)
(compose-list fns)
)
(define (FizzBuzz2 m n)
(map (compose (carbonate 15 'FizzBuzz) (carbonate 5 'Buzz) (carbonate 3 'Fizz)) (number-interval m n))
)
The design pattern I'm talking about concerns multi-arg Scheme functions like
compose, above. The composition of a list of functions is the composition of the first with the composition of the rest. But I can't see how Scheme's multi-argument-function syntax is amenable to the natural recursion. So I have to write the compose-list helper function.I've had to do this a few times writing Scheme functions, so maybe it's a design pattern! Mark Dominus has pointed out that patterns are a sign of weaknesses in programming languages. So, is this a real weakness in Scheme? Is there another way to recurse with a multi-argument function?
No comments:
Post a Comment