Created
May 3, 2015 02:46
-
-
Save bheeshmar/b1c210b19c410c124cfa to your computer and use it in GitHub Desktop.
Many faces of Factorial in Elixir
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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