I really liked what I saw when I read about the elixir programming language. So I'm diving in and figuring this thing out!
I come from object oriented programming so I don't know what I'm doing (yet) with this whole functional thing, but I'm FIRED UP TO LEARN!
Starting off my journey playing with the FizzBuzz problem.
defmodule FizzBuzz do def start(numbers) do numbers |> Enum.map &parse(&1) end defp parse(number) do cond do rem(number,3) == 0 and rem(number,5) == 0 -> IO.puts "FizzBuzz" rem(number,3) == 0 -> IO.puts "Fizz" rem(number,5) == 0 -> IO.puts "Buzz" true -> IO.puts number end end end FizzBuzz.start(1..100)
First I wrote it using almost an
elseif style, taking advantage of elixir's
cond block. This looks similar to how I would do it in ruby.
Next I want to explore solving the problem using pattern matching.
defmodule FizzBuzzPM do def start(numbers) do numbers |> Enum.map(&parse(rem(&1, 3),rem(&1, 5), &1)) end def parse(0, 0, _), do: IO.puts "FizzBuzz" def parse(0, _, _), do: IO.puts "Fizz" def parse(_, 0, _), do: IO.puts "Buzz" def parse(_, _, num), do: IO.puts num end FizzBuzzPM.start(1..100)
I used the shorthand
& when passing the params to
Enum.map which I totally dig. Was much nicer than having to type out
|> Enum.map(fn x -> parse(rem(x, 3),rem(x, 5), x) end)
I kinda like the first example better for this problem, just because to me its easier to tie the test to the result. But man, pattern matching is awesome my head is already swimming with so many ideas of how to apply it to problems!