15 Jul 2013, 03:42
Dave_gnome_head_isolated_pragsmall

Dave Thomas (340 posts)

  • Rewrite the FizzBuzz example using case.

A Possible Solution</summary>

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

</details>

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 (340 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>

17 Nov 2014, 00:01
Generic-user-small

Elliot Finley (11 posts)

My try at this:

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

  defp fizzbuzz(n) do
    test = [rem(n, 3), rem(n, 5)]
    case test do
      [0, 0] -> "FizzBuzz"
      [0, _] -> "Fizz"
      [_, 0] -> "Buzz"
      _      -> n
    end
  end
end
30 Dec 2014, 11:46
Generic-user-small

Pierre Sugar (56 posts)

defmodule FizzBuzz do

  def upto(n), do: fizzbuzz(n, [])
  def fizzbuzz(0, result), do: result
  def fizzbuzz(n, result) do
    val = case {rem(n,3), rem(n,5), n} do
      {0,0,_} -> "FizzBuzz"
      {0,_,_} -> "Fizz"
      {_,0,_} -> "Buzz"
      {_,_,n} -> n
    end
    fizzbuzz(n-1, [val | result])
  end

end
  You must be logged in to comment