Question

I'm working through "Programming Elixir" and I came across the exercise headed "Exercise: Functions 2". Long story short, basically code a function which emits Fizzbuzz if the first two parameters are 0, Fizz if the first param is 0, Buzz if the second param is 0 and the third param if neither of the first two are zero. I came up with this:

fizzbuzztest = fn
   {0,0,_} -> "FizzBuzz"
   {0,_,_} -> "Fizz"
   {_,0,_} -> "Buzz"
   {_,_,v} -> "#{v}"
end

Called like so:

fizzbuzztest.({0,0,8}) # "FizzBuzz"

But I'm wondering--is there some way to do this without having to tuple the parameters? It seems there should be some way to pass three arguments and work the pattern match but I haven't found it yet. Any suggestions from those more experienced with Elixir would be welcome.

Was it helpful?

Solution

You can solve this particular exercise with:

fizzbuzztest = fn
   0,0,_ -> "FizzBuzz"
   0,_,_ -> "Fizz"
   _,0,_ -> "Buzz"
   _,_,v -> "#{v}"
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top