top | item 8447395

(no title)

robdor | 11 years ago

I haven't looked too deeply into Rust yet, but was able to understand this coming from Elixir. Pattern matching makes for a beautiful solution. This is a similar solution in Elixir:

  fizzbuzz = fn(x) ->
    case {rem(x, 3) == 0, rem(x, 5) == 0} do
      {true, false} -> IO.puts "fizz"
      {false, true} -> IO.puts "buzz"
      {true, true}  -> IO.puts "fizzbuzz"
      _             -> IO.puts x
    end
  end

  Enum.each Range.new(1, num), fizzbuzz
Since functions are also pattern matched in Elixir (and Erlang!) it could also be done without using case and handled purely as functions.

discuss

order

adamkittelson|11 years ago

Yeah, it's also fun that you can do it in a multiple function head pattern matchy way

  defmodule FizzBuzz do
    def fizzbuzz(x),          do: fizzbuzz(x, {rem(x, 3), rem(x, 5)})
    def fizzbuzz(_x, {0, 0}), do: IO.puts "fizzbuzz"
    def fizzbuzz(_x, {0, _}), do: IO.puts "fizz"
    def fizzbuzz(_x, {_, 0}), do: IO.puts "buzz"
    def fizzbuzz(x,  {_, _}), do: IO.puts x
  end

  Enum.each Range.new(1, 100), &FizzBuzz.fizzbuzz/1

or in a more ruby-esque fashion

  (1..100) |> Enum.each fn(x) ->
    cond do
      rem(x, 3) == 0 and rem(x, 5) == 0 ->
        IO.puts "fizzbuzz"
      rem(x,5) == 0 ->
        IO.puts "buzz"
      rem(x,3) == 0 ->
        IO.puts "fizz"
      true ->
        IO.puts x
    end
  end