Skip to content

Instantly share code, notes, and snippets.

@bheeshmar
Created May 3, 2015 02:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bheeshmar/b1c210b19c410c124cfa to your computer and use it in GitHub Desktop.
Save bheeshmar/b1c210b19c410c124cfa to your computer and use it in GitHub Desktop.
Many faces of Factorial in Elixir
defmodule Foo do
# Use case matching
def fact1(n) do
case n do
1 -> 1
_ -> n * fact1(n-1)
end
end
# Use conditionals
def fact2(n) do
if n == 1 do
1
else
n * fact2(n-1)
end
end
# Use reduce
def fact3(n) do
Enum.reduce(1..n, 1, &(&1 * &2))
end
# Use reduce with anonymous function
def fact4(n) do
Enum.reduce(1..n, 1, fn(a,b) -> a * b; end)
end
# Use pattern matching
def fact5(1), do: 1
def fact5(n), do: n * fact5(n-1)
end
IO.puts Foo.fact1(5)
IO.puts Foo.fact2(5)
IO.puts Foo.fact3(5)
IO.puts Foo.fact4(5)
IO.puts Foo.fact5(5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment