HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

FizzBuzz - officially now in CLISP

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
nowclispofficiallyfizzbuzz

Problem

I had to jump on the bandwagon for this one. The task does a great job of helping you learn a language you're unfamiliar with.

So today I present you with my version of the infamous FizzBuzz game in Common Lisp. This is really the first "program" I've made in CLISP, and even though it's pretty small, I'm quite proud!!

I'd really love to know if there's an even easier way to make the same functionality. I notice a lot of repetition in terms of is-multiple, so if anyone has any ideas how I could DRY up all that, I'd appreciate it. Also, is there a formatting standard for symbol names and such in Lisp?

fizzbuzz.lisp

(defun is-multiple (i against)
  (= (mod i against) 0))
(defun num-action (i)
  (cond ((and (is-multiple i 3) (is-multiple i 5)) (print "FizzBuzz"))
    ((is-multiple i 3) (print "Fizz"))
    ((is-multiple i 5) (print "Buzz"))
    (T (print i))))
(dotimes (i 101) (num-action i))


Can it be cleaned up any further?

Solution

Do not recompute is-multiple repeatedly by either binding the value:

(defun num-action (i)
  (let ((i3 (is-multiple i 3))
        (i5 (is-multiple i 5)))
    (cond ((and i3 i5) (print "FizzBuzz"))
          (i3 (print "Fizz"))
          (i5 (print "Buzz"))
          (T (print i)))))


or by using if:

(defun num-action (i)
  (if (is-multiple i 3)
      (if (is-multiple i 5)
          (print "FizzBuzz")
          (print "Fizz"))
      (if (is-multiple i 5)
          (print "Buzz")
          (print i))))


PS. please fix indentation

Code Snippets

(defun num-action (i)
  (let ((i3 (is-multiple i 3))
        (i5 (is-multiple i 5)))
    (cond ((and i3 i5) (print "FizzBuzz"))
          (i3 (print "Fizz"))
          (i5 (print "Buzz"))
          (T (print i)))))
(defun num-action (i)
  (if (is-multiple i 3)
      (if (is-multiple i 5)
          (print "FizzBuzz")
          (print "Fizz"))
      (if (is-multiple i 5)
          (print "Buzz")
          (print i))))

Context

StackExchange Code Review Q#56890, answer score: 7

Revisions (0)

No revisions yet.