# Fizz Buzz in Scheme

I learned about a children’s game called Fizz Buzz today. It turns out that Fizz Buzz is a fairly common programming task that comes up during programming interviews.

Since I am learning to program, I decided to give it a shot.

Here is one way to code a Fizz Buzz procedure in Scheme.
It took me about 5 minutes to think out the solution to this and write the code.

```(define (fizzbuzz x)
(cond ((and (equal? (remainder x 3) 0) (equal? (remainder x 5) 0)) 'fizzbuzz)
((equal? (remainder x 3) 0) 'fizz)
((equal? (remainder x 5) 0) 'buzz)
(else se x)))```

Update 2020-05-28:

I learned about a new notation called “let” today.

I figured I could improve my Fizz Buzz code by adding “let” to the previous code. This way it becomes easier to alter the “fizz”, “buzz”, and “fizzbuzz” values since they would only have to be altered in one place instead of changing the number in all places in the code.

This was my first solution with “let“:

```(define (fizzbuzz x)
(let ((fizz 3)
(buzz 5))
(cond ((and (equal? (remainder x fizz) 0) (equal? (remainder x buzz) 0)) 'fizzbuzz)
((equal? (remainder x fizz) 0) 'fizz)
((equal? (remainder x buzz) 0) 'buzz)
(else se x))))```

I thought some more about it and figured I could improve on the code even more – rid it of the redundant parts.

Result:

```(define (fizzbuzz x)
(let ((fizz 3)
(buzz 5))
(let ((fizzname (equal? (remainder x fizz) 0))
(buzzname (equal? (remainder x buzz) 0)))
(cond ((and fizzname buzzname) 'fizzbuzz)
(fizzname 'fizz)
(buzzname 'buzz)
(else se x)))))```

Update 2020-05-29:

Adding some explanation to the evolution of above code.

The first code did what it was supposed to do. It gave the right answers to Fizz Buzz for numbers divisible with 3 and 5.

In the next step I added the “let” notation. Adding “let” made the code better because it made it easier to change the numbers from 3 and 5 to any other numbers.
By adding “let” one only needs to change the numbers in one single place of the code. Without “let” one would have to change every singel “3” and “5” that appears in the entire code. Thus there is less room for error after adding “let“. An error would be to eg miss to change one “3” in the code.

In the final step I added “let” to recurring parts of the code as well. By doing this, recurring parts of the code only need to be evaluated once instead of multiple times. This makes the code more efficient.

This site uses Akismet to reduce spam. Learn how your comment data is processed.