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] { pf: platform "https://github.com/roc-lang/basic-cli/releases/download/0.17.0/lZFLstMUCUvd5bjnnpYromZJXkQUrdhbva4xdBInicE.tar.br" } import pf.Stdout main = List.range { start: At 1, end: At 100 } |> List.map fizzBuzz |> Str.joinWith "," |> 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. fizzBuzz : I32 -> Str fizzBuzz = \n -> fizz = n % 3 == 0 buzz = n % 5 == 0 if fizz && buzz then "FizzBuzz" else if fizz then "Fizz" else if buzz then "Buzz" else Num.toStr n ## Test Case 1: not a multiple of 3 or 5 expect fizzBuzz 1 == "1" expect fizzBuzz 7 == "7" ## Test Case 2: multiple of 3 expect fizzBuzz 3 == "Fizz" expect fizzBuzz 9 == "Fizz" ## Test Case 3: multiple of 5 expect fizzBuzz 5 == "Buzz" expect fizzBuzz 20 == "Buzz" ## Test Case 4: multiple of both 3 and 5 expect fizzBuzz 15 == "FizzBuzz" expect fizzBuzz 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.