Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Last active December 27, 2017 06:01
Show Gist options
  • Save CMCDragonkai/7cd518eeb69be9fb6c32 to your computer and use it in GitHub Desktop.
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
// 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
@mac-chaffee
Copy link

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.

@CMCDragonkai
Copy link
Author

Sounds like the pattern matching system changed?

@CMCDragonkai
Copy link
Author

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