Re: A style question



On Feb 28, 11:31 am, "justinhj" <justi...@xxxxxxxxx> wrote:
On Feb 28, 10:51 am, "justinhj" <justi...@xxxxxxxxx> wrote:



On Feb 27, 11:31 pm, job-271842...@xxxxxxxxxxxxxx wrote:

justinhj wrote:
(defun multiple(x n)
(= 0 (mod x n)))

(defun output-multiple(x n str)
(if (and (multiple x n) (princ str))
1
0))

(defun fizzbuzz(n)
(loop for x from 1 to n do
(if (> (+ (output-multiple x 3 "fizz") (output-multiple x 5
"buzz")) 0)
(format t "~%"))))

Hmm.. this doesn't seem to work.

[1]> (defun multiple(x n)
(= 0 (mod x n)))
MULTIPLE
[2]>
(defun output-multiple(x n str)
(if (and (multiple x n) (princ str))
1
0))
OUTPUT-MULTIPLE
[3]>
(defun fizzbuzz(n)
(loop for x from 1 to n do
(if (> (+ (output-multiple x 3 "fizz") (output-multiple x 5
"buzz")) 0)
(format t "~%"))))
FIZZBUZZ
[4]> (fizzbuzz 12)
fizz
buzz
fizz
fizz
buzz
fizz
NIL
[5]>

Unless I'm misunderstanding something what doesn't work? The output is
correct.

Justin

I'm not having much luck trying to make it elegant and concise but I
quite like this recursive version...

(defun fizzbuzz2(n)
(labels ((fizzbuzz-rec (current last fizz buzz)
(let ((output nil))
(if (= 0 fizz)
(push "fizz" output))
(if (= 0 buzz)
(push "buzz" output))
(if output
(format t "~{~a~}~%" output))
(unless (= current last)
(fizzbuzz-rec (1+ current) last (mod (1-
fizz) 3) (mod (1- buzz) 5))))))
(fizzbuzz-rec 1 n (1- 3) (1- 5))))

CL-USER> (fizzbuzz2 15)
fizz
buzz
fizz
fizz
buzz
fizz
buzzfizz

Justin

Note: just realised you have to swap the order of the buzz print with
the fizz print to get the correct output ;)

Justin

.



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: so forth is useless except for limited mem environments?
    ... Here are the codes I was comparing in Fizz Buzz... ... ala Frank Buzz ... the two flags with an OR and 0= rather than "invert swap invert and". ... I would prefer factoring over if-then-else cascades ...
    (comp.lang.forth)
  • Re: so forth is useless except for limited mem environments?
    ... Here are the codes I was comparing in Fizz Buzz... ... ala Frank Buzz ... the two flags with an OR and 0= rather than "invert swap invert and". ...
    (comp.lang.forth)
  • Re: A style question
    ... (if fizz (format t "Fizz")) ... (if buzz (format t "Buzz")) ... but is anything like the boolean bit shifting technique used in the Python code above possible in Lisp? ...
    (comp.lang.lisp)
  • Re: A style question
    ... (format t "~%")))) ... (defun output-multiple(x n str) ...
    (comp.lang.lisp)