Re: A style question
- From: job-271842874@xxxxxxxxxxxxxx
- Date: Tue, 27 Feb 2007 22:45:41 -0500
Paul Wallich wrote:
job-271842874@xxxxxxxxxxxxxx wrote:(defun fizz-buzz (n)
(do ((i 1 (+ i 1)))
((> i n))
(let
((fizz (= 0 (mod i 3)))
(buzz (= 0 (mod i 5))))
(if fizz (format t "Fizz"))
(if buzz (format t "Buzz"))
(format t "~A~%"
(if (or fizz buzz) "" i)))))
In both cases, what the local variables add in supposed elegance seems to me lost by the clunkiness of setting them in the first place (which you haven't done correctly).
Can you elaborate about how I incorrectly set the local variables? The program functions correctly, so maybe you're referring to using zerop instead?
I'd probably brute-force the problem with a simple cond with a nested conditions, along the lines of
(cond ((zerop (mod i 5))
(cond ((zerop (mod i 3)) (print "FizzBuzz"))
(t (print "Buzz"))))
((zerop (mod i 3))
(print "Fizz"))
(t (print i)))
Someone else can do the loop version, the version with a macro that generates any possible fizz-buzz function of two small integers, the ver
I haven't made it to the chapter on macros yet, but would it be better Lisp style to write a macro to be able to handle any two integers, or just add 2 parameters e.g. (defun fizz-buzz (n a b) ... ), or maybe it would be more Lisp-like to pass a list as the 2nd param (defun fizz-buzz (n lst) ... ) where each element in the list would contain an integer and the replacement string - something like:
(defun fizz-buzz (n lst)
(do ((i 1 (+ i 1)))
((> i n))
(let
((fizzed nil))
(dolist (obj lst)
(let ((a (car obj))
(str (car (cdr obj))))
(when (zerop (mod i a))
(princ str)
(setf fizzed t))))
(if (not fizzed)
(princ i))
(terpri))))
(fizz-buzz 100 '((3 "Fizz") (5 "Buzz")))
I know this is *** ugly, but the principle of generalizing with a 2nd list parameter seems like a reasonable enhancement. Since I'm not to the point of "thinking in Lisp", this would be my first approach, but maybe macros would be the way to go here. Hopefully, I'll have a feel for that after chapter 10 :)
Brian
.
- References:
- A style question
- From: job-271842874
- Re: A style question
- From: Paul Wallich
- A style question
- Prev by Date: Re: A style question
- Next by Date: Re: A style question
- Previous by thread: Re: A style question
- Next by thread: Re: A style question
- Index(es):