Re: A style question
- From: Paul Wallich <pw@xxxxxxxxx>
- Date: Tue, 27 Feb 2007 21:21:26 -0500
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
.
- Follow-Ups:
- Re: A style question
- From: Dan Bensen
- Re: A style question
- From: job-271842874
- Re: A style question
- From: Ken Tilton
- Re: A style question
- References:
- A style question
- From: job-271842874
- 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):
Relevant Pages
|
|