Re: A style question





Paul Wallich wrote:
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)))

I would object to using cond to implement if, and the redundant code testing for (mod i 3) and associating it with Fizz.

Otherwise, I am bothered by the spec. Is the FizzBuzz on 15 tied to it factoring to 3 and 5 and those substitutions, or is that coincidental? ie, Could an RFE come thru for 15 to translate to Bang? Also, is this list expected to expand? If so, will the test always be even divisibility?

This is how I get thrown out of most tech interviews.

kt

--
"I don't like being tested."
-- Tangina, Poltergeist
.