FizzBuzz in Elixir
Exercise: Functions-2:
Write a function that takes three arguments. If the first two are zero, return “FizzBuzz”. If the first is zero, return “Fizz”. If the second is zero return “Buzz”. Otherwise return the third argument. Do not use any language features that we haven’t yet covered in this book.
Exercise: Functions-3:
The operator rem(a, b) returns the remainder after dividing a by b. Write a function that takes a single integer (n) calls the function in the previous exercise, passing it rem(n,3), rem(n,5), and n. Call it 7 times with the arguments 10, 11, 12, etc. You should get “Buzz, 11, Fizz, 13, 14, FizzBuzz”, 16”.
fizz_buzz = function do
(0, 0, _) -> "FizzBuzz"
(0, _, _) -> "Fizz"
(_, 0, _) -> "Buzz"
(_, _, x) -> x
end
check_fizz_buzz = function do
(n) -> fizz_buzz.(rem(n,3), rem(n,5),n)
end
Enum.each([10,11,12,13,14,15,16], fn(n) ->
IO.puts "FizzBuzz(#{n}):: #{check_fizz_buzz.(n)}"
end)
output:
FizzBuzz(10):: Buzz
FizzBuzz(11):: 11
FizzBuzz(12):: Fizz
FizzBuzz(13):: 13
FizzBuzz(14):: 14
FizzBuzz(15):: FizzBuzz
FizzBuzz(16):: 16
Challenge from Programming Elixir
Written by Clint Shryock
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Elixir
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#