Last active
December 27, 2017 06:01
-
-
Save CMCDragonkai/7cd518eeb69be9fb6c32 to your computer and use it in GitHub Desktop.
Elixir: Tail Recursive Factorial - Avoids growing stack space linearly. This is related to dynamic programming: http://stackoverflow.com/q/12649970/582917
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
// factorial tail recursive (Elixir style) | |
// 4! means 1*2*3*4, we can ignore 1, which makes it 2*3*4 = 24 | |
def factorial(number) do | |
factorial(number, 1) | |
end | |
def factorial(number, product) do | |
factorial(number - 1, product * number) | |
end | |
def factorial(1, product) do | |
product | |
end |
Sounds like the pattern matching system changed?
Just change the order between the last and second definitions.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Something may have changed in recent versions of elixir. I get
warning: this clause cannot match because a previous clause at line 9 always matches
on line 13 and this causes an infinite loop now.