Skip to content

Instantly share code, notes, and snippets.

@jasondown
Created September 2, 2016 04:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasondown/5bc2ec9f55cdbc93ed5fa7128a3cc882 to your computer and use it in GitHub Desktop.
Save jasondown/5bc2ec9f55cdbc93ed5fa7128a3cc882 to your computer and use it in GitHub Desktop.
Elixir Factorial - Pattern Matching and Recursion
defmodule MyMath do
def factorial(n), do: factorial(n, 1)
def factorial(0, acc), do: acc
def factorial(n, acc) do
factorial(n - 1, acc * n)
end
end
@jasondown
Copy link
Author

Sample usage:
IO.inspect(for n <- 0..10, do: MyMath.factorial(n))

[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment