I just started reading about Elixir few days ago, an I’m fascinated. I programmed in Python, Java, and i work in Ruby. Never before i wrote in functional language.
I read most of tutorial, did elixir koans, and now i tried project euler
defmodule One do
def sum_of_multiples(n) do
n = n - 1
if n == 0 do
0
else
if rem(n, 3) == 0 do
sum_of_multiples(n, n - 1)
else
if rem(n, 5) == 0 do
sum_of_multiples(n, n - 1)
else
sum_of_multiples(0, n - 1)
end
end
end
end
def sum_of_multiples(accumulator, n) do
if n == 0 do
accumulator
else
if rem(n, 3) == 0 do
sum_of_multiples(accumulator + n, n - 1)
else
if rem(n, 5) == 0 do
sum_of_multiples(accumulator + n, n - 1)
else
sum_of_multiples(accumulator, n - 1)
end
end
end
end
end
IO.puts One.sum_of_multiples(1000)
Above is my working code. How can i rewrite this to use pattern matching instead of this ugly if else?
I tried like this also:
Enum.map(1..999, fn n -> if rem(n, 3) == 0 or rem(n, 5) == 0, do: n, else, do: 0, end) |> Enum.sum |> IO.puts
But first of all there is syntax error i’m unable to correct on my own
I somehowo managed to do that:
Enum.map(1..999, fn n -> if(rem(n, 3) == 0 or rem(n, 5) == 0, do: n, else: 0) end) |> Enum.sum |> IO.puts
But still don’t know how to rewrite those functions