Re: A style question



job-271842874@xxxxxxxxxxxxxx wrote:
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

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

Another friend of mine commenting on the same FizzBuzz thread supplied the following Python code. It certainly is concise:

for i in xrange(1,101):
print(str(i), "Fizz", "Buzz", "FizzBuzz")[(i%3==0)|(i%5==0)<<1]

I thought about retrofitting my Ruby version as an exercise, but alas, Ruby doesn't allow shifting truth to the left :)

Forgive my ignorance, but is anything like the boolean bit shifting technique used in the Python code above possible in Lisp? No big loss if it isn't, just curious.

I suppose it's unreasonable to expect the Lisp version to be as concise as the Python version - not only is this a toy example, but I think a language with more syntax will be able to provide more brevity in certain situations. That's a tradeoff I'm willing to accept given the benefits of a syntax that's more readily parsed and manipulated.

Brian

.



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
    ... (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: A style question
    ... 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 and having a *couple hours* of Lisp under my belt, I cranked out a Lisp version. ... (if fizz (format t "Fizz")) ...
    (comp.lang.lisp)
  • Re: Browsing text ; Python the right tool?
    ... The "specs" I'm used to dealing with are inconsistent enough that it's ... specifications into a regular, machine-readable format. ... than your massaging of specification data -- I'm just massaging it ... into Python code instead of CSV tables. ...
    (comp.lang.python)