0

I creating a factorial function in Elixir:

def factorial(0), do: 1
def factorial(n) when n > 0, do: n * factorial(n - 1)

First of all, I love how straightforward and elegant the solution is in Elixir. But, there is one thing that I do not understand. On the second line, I used this code: do: n * factorial(n - 1). Say we give the function an argument of 5. that line would look like this. do: 5 * factorial(5 - 1) so why doesn't the answer just come out to this: 20? Basically my question is. How does it know to continue to the base case? We aren't explicitly telling the program to continue until 0, are we? If someone could break this down for that would be awesome!

1 Answer 1

3

Yes, you are explicitly telling it to continue until 0. This is what the first clause does def factorial(0), do: 1. That causes will eventually get called when when you've decremented to 0. It is the clause that breaks out of the recursion (returns 1 and does not call factorial again).

Also note the when n > 0 guard is only there to catch the case where you call factorial on a negative number. It is not used in the case of factorial(5) for example.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.