A style question



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

(fizz-buzz 100)

By the way, it seems more folks recommend starting with "Practical Common Lisp" instead of "ANSI Common Lisp" (when both are mentioned), but being a newbie myself, it seems that the latter is a better introduction to the language.

Brian
.



Relevant Pages

  • Re: Lisp vs. I/O
    ... > | binary type I think it will equal it for brevity. ... The other situation is when you need to parse a specific binary format ... the difference between Common Lisp and C is not so ... Hopefully the implementation will compile this down to something ...
    (comp.lang.lisp)
  • Re: tagbody vs. defun
    ...   (format t "one~%") ... I think _Practical Common Lisp_, available at http://www.gigamonkeys.com/book/, ... PROGN and TAGBODY both have their place, ...
    (comp.lang.lisp)
  • Re: Pretty printing sexps
    ... I can get this program to dump the output as one long string of sexps but that isn't a format that makes it easy to see any problems with my parser. ... Common Lisp Document Repository: http://cdr.eurolisp.org ...
    (comp.lang.lisp)
  • Re: split-sequence
    ... > passing it together with a format string to a formatter, ... CL-INTERPOL - string interpolation for Common Lisp ...
    (comp.lang.lisp)
  • Re: Beyond CL?
    ... >>> You may be surprised about what you learn about programming language design. ... >>> Common Lisp is very, very, very well designed. ... I have a better LOOP and FORMAT. ...
    (comp.lang.lisp)