Re: A style question
- From: "Joel Wilsson" <joel.wilsson@xxxxxxxxx>
- Date: 28 Feb 2007 00:17:00 -0800
On Feb 28, 7:09 am, job-271842...@xxxxxxxxxxxxxx wrote:
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 :)
While it's "nice" in this case, I think it's a sign of a weak type
system.
Even Java has a boolean type.
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.
No, but of course you could easily make it.
(flet ((num-zerop (x)
(if (zerop x)
1
0)))
(defun fizz-buzz (n)
(dotimes (i (1+ n))
(format t "~A~%" (nth (logior (num-zerop (mod i 3))
(ash (num-zerop (mod i 5)) 1))
(list i "Fizz" "Buzz" "FizzBuzz"))))))
I suppose it's unreasonable to expect the Lisp version to be as concise
as the Python version
Due to the nature of the problem I don't think any language where
equality
testing returns true booleans can be shorter than that Python version.
This is closer to Common Lisp style I think, and slightly more
verbose:
(defun fizz-buzz (n)
(dotimes (i (1+ n))
(format t "~A~%" (nth (+ (if (zerop (mod i 3)) 1 0)
(if (zerop (mod i 5)) 2 0))
(list i "Fizz" "Buzz" "FizzBuzz")))))
In my opinion some of the first versions posted in this thread were
the
best, since they were much easier to read and understand. We're just
doing obfuscated stuff now, might as well go all out:
(defun fizz-buzz (n)
(format t "~{~A~%~}" (reduce (lambda (h r)
(cons (nth (reduce (lambda (x y)
(if (zerop (mod
h (1+ (* 2 y))))
(+ y x)
x))
'(1 2) :initial-
value 0)
(list h "Fizz" "Buzz"
"FizzBuzz")) r))
(reduce (lambda (x y)
(cons (decf n) y))
(make-list (incf n)) :from-end
t)
:from-end t :initial-value nil)))
As for your question about loop, you really should learn it. Even if
you don't use it much yourself, plenty of code written by others does.
Regards,
Joel
.
- References:
- A style question
- From: job-271842874
- Re: A style question
- From: job-271842874
- A style question
- Prev by Date: Re: "The Swine before Perl" location?
- 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
|