<loop>
<fb>
<fb-cond>
<require>
<*>

Fizzbuzz in Literate Racket

Fizzbuzz is a simple program that counts from 1 to 100 replacing multiples of 3 with "Fizz", multiples of 5 with "Buzz" and multiples of both 3 and 5 with "FizzBuzz".

Essentially, we want to map over the numbers from 1 to 100, applying a function that converts the multiples of 3 and 5 to the correct word, and then print the result.

<loop> ::=
(for ([i (stream-map fb (in-range 1 101))])
  (printf "~a\n" i))

The function fb is used to transform numbers into the correct string, e.g. "1", "2", "Fizz" ...

Inside fb we have a local function definition; divides, returns true if the second argument divides into the first.

<fb> ::=
(define (fb n)
  (local [(define (divides? n m) (= 0 (modulo n m)))]
    <fb-cond>))

The main body of the function is a single conditional. If the argument is divisible by both 3 we return "Fizz" and if it is divisible by 5 we return "Buzz". If it is divisible by both 3 and 5 (equivalent to being divisible by 15) we return "FizzBuzz". If the number is not divisible by 3 or 5 then we simply convert the number into a string.

(cond [(divides? n 15) "FizzBuzz"]
      [(divides? n 5) "Buzz"]
      [(divides? n 3) "Fizz"]
      [else (number->string n)])

scribble-lp uses racket/base rather than racket, so we need to include the modules for the local and stream-map functions.

(require racket/local)
(require racket/stream)

The <*> chunk is then used to pull all the parts of the program together.

<*> ::=