15 Jul 2013, 03:42
Dave_gnome_head_isolated_pragsmall

Dave Thomas (337 posts)

  • Rewrite the FizzBuzz example using case.
A Possible Solution
defmodule FizzBuzz do

  def upto(n) when n > 0 do
    1..n |> Enum.map(fizzbuzz(&1))
  end

  defp fizzbuzz(n) do
    case { rem(n, 3), rem(n, 5), n } do
      { 0, 0, _ } -> "FizzBuzz"
      { 0, _, _ } -> "Fizz"
      { _, 0, _ } -> "Buzz"
      { _, _, n } -> n
    end
  end
end
18 Jun 2014, 13:51
Badgestrongmad_pragsmall

Brett DiFrischia (1 post)

Hi Dave,

First, thank you for a(nother) great book!

I’m wondering why you included n in the tuple within fizzbuzz. It does not change bindings within the function, so wouldn’t the following be a bit cleaner:

defmodule FizzBuzz do

  def upto(n) when n > 0 do
    1..n |> Enum.map(&_fizzbuzz_2/1)
  end

  defp _fizzbuzz_2(n) do
    case { rem(n, 3), rem(n, 5) } do
      { 0, 0 } -> "FizzBuzz"
      { 0, _ } -> "Fizz"
      { _, 0 } -> "Buzz"
      _        -> n
    end
  end

end

Update: Is there a (simple) way to hide our code in the forums? I’d prefer not to spoil the exercise for others.

Update 2: Thank you!

03 Nov 2013, 09:55
Dave_gnome_head_isolated_pragsmall

Dave Thomas (337 posts)

I did it simply because it logically felt better to me to pass it in the match, rather than in the closure. I could be swayed either way.

To hide something enclose it in <details markdown=”block”>…</details>

  You must be logged in to comment