Re:Why your first Rust FizzBuzz implementation may not work
by robdor on Sunday October 12, 2014 @11:37PM
(#8447395)
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:
Since functions are also pattern matched in Elixir (and Erlang!) it could also be done without using case and handled purely as functions.
[ Parent
| on HN ]
Re:Why your first Rust FizzBuzz implementation may not work
by adamkittelson on Monday October 13, 2014 @01:16AM
(#8447583)
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