I am trying to understand why a recursion function is behaving the way it is.
let rec fact = function
|0 -> 1
|n -> n * fact(n-1);;
When i execute:
fact 4;;
it responds:
val it : int = 24
which is ofcourse Is correct since 1*2*3*4 = 24
What i don't get is this piece of code:
|n -> n * fact(n-1);;
I don't get why It doesn't calculate:
4 -> 4 * (4-1)
4 -> 4 * 3
4 -> 12
My guess Is I am misunderstanding the definition of n
can someone do the honor and enlighten me?
That would be true if the definition were n -> n * (n - 1) but it is making a recursive call to fact so it is:
4 * fact(4 - 1)
=> 4 * fact(3)
=> 4 * (3 * fact(2))
=> 4 * (3 * (2 * fact(1)))
=> 4 * (3 * (2 * (1 * fact(0))))
=> 4 * (3 * (2 * (1 * 1)))
=> 4 * (3 * (2 * 1))
=> 4 * (3 * 2)
=> 4 * 6
=> 24
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With