Re: A style question



job-271842874@xxxxxxxxxxxxxx wrote:
A friend passed on an article regarding the difficulty job candidates had in producing even simple programs (simple as in should take a minute or less). One example was a program to print the numbers 1 to 100 except that "Fizz" should be substituted for numbers divisible by 3, "Buzz" should be substituted for numbers divisible by 5, and "FizzBuzz" should be substituted for numbers divisible by both 3 and 5.

So, having received my "ANSI Common Lisp" and "Practical Common Lisp" books two days ago (still waiting for "Structure and Interpretation of Computer Programs") and having a *couple hours* of Lisp under my belt, I cranked out a Lisp version. It seems a bit clunky, so I thought I'd see if anyone had suggestions for improvements.

Here's a Ruby version for comparison:

def fizz_buzz n
1.upto(n) do |i|
print "Fizz" if fizz = (i % 3) == 0
print "Buzz" if buzz = (i % 5) == 0
puts fizz || buzz ? "" : i
end
end

fizz_buzz 100

and the Lisp version

(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).

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
.



Relevant Pages

  • Re: A style question
    ... (if fizz (format t "Fizz")) ... (if buzz (format t "Buzz")) ... You have missed that what I am driving at is good programming, you are caught up in cleverness, the road to hell in programming. ...
    (comp.lang.lisp)
  • Re: A style question
    ... (if fizz (format t "Fizz")) ... (if buzz (format t "Buzz")) ... but is anything like the boolean bit shifting technique used in the Python code above possible in Lisp? ...
    (comp.lang.lisp)
  • Re: A style question
    ... (format t "~%")))) ... (defun output-multiple(x n str) ...
    (comp.lang.lisp)
  • Re: A style question
    ... (format t "~%")))) ... (defun output-multiple(x n str) ...
    (comp.lang.lisp)
  • Re: Rewrap "> " lines from file ?
    ... Common Lisp, as that is much easier to use for stand-alone processing. ... Anyway, once you have paragraphs, you can use a fancy Common Lisp format ... A fancier form of this function would allow you to specify the prefix ... language, then what you should do is write a rule-based reformatter, and ...
    (comp.lang.lisp)