FizzBuzz

A Roc solution to the popular FizzBuzz interview problem:

Print the integers from 1 to 100, replacing multiples of three with "Fizz", multiples of five with "Buzz", and multiples of both three and five with "FizzBuzz".

Code

app [main!] { cli: platform "https://github.com/roc-lang/basic-cli/releases/download/0.19.0/Hj-J_zxz7V9YurCSTFcFdu6cQJie4guzsPMUi5kBYUk.tar.br" }

import cli.Stdout

main! = |_args|
    List.range({ start: At(1), end: At(100) })
    |> List.map(fizz_buzz)
    |> Str.join_with(",")
    |> Stdout.line!

## Determine the FizzBuzz value for a given integer.
## Returns "Fizz" for multiples of 3, "Buzz" for
## multiples of 5, "FizzBuzz" for multiples of both
## 3 and 5, and the original number for anything else.
fizz_buzz : I32 -> Str
fizz_buzz = |n|
    fizz = n % 3 == 0
    buzz = n % 5 == 0

    if fizz and buzz then
        "FizzBuzz"
    else if fizz then
        "Fizz"
    else if buzz then
        "Buzz"
    else
        Num.to_str(n)

## Test Case 1: not a multiple of 3 or 5
expect fizz_buzz(1) == "1"
expect fizz_buzz(7) == "7"

## Test Case 2: multiple of 3
expect fizz_buzz(3) == "Fizz"
expect fizz_buzz(9) == "Fizz"

## Test Case 3: multiple of 5
expect fizz_buzz(5) == "Buzz"
expect fizz_buzz(20) == "Buzz"

## Test Case 4: multiple of both 3 and 5
expect fizz_buzz(15) == "FizzBuzz"
expect fizz_buzz(45) == "FizzBuzz"

Output

Run this from the directory that has main.roc in it:

$ roc main.roc
1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz,16,17,Fizz,19,Buzz,Fizz,22,23,Fizz,Buzz,26,Fizz,28,29,FizzBuzz,31,32,Fizz,34,Buzz,Fizz,37,38,Fizz,Buzz,41,Fizz,43,44,FizzBuzz,46,47,Fizz,49,Buzz,Fizz,52,53,Fizz,Buzz,56,Fizz,58,59,FizzBuzz,61,62,Fizz,64,Buzz,Fizz,67,68,Fizz,Buzz,71,Fizz,73,74,FizzBuzz,76,77,Fizz,79,Buzz,Fizz,82,83,Fizz,Buzz,86,Fizz,88,89,FizzBuzz,91,92,Fizz,94,Buzz,Fizz,97,98,Fizz,Buzz

You can also use roc test to run the tests.