I've been trying to learn SML NJ (standard ML New Jersey) and I've come across a function that I understand to be recursion, but can't quite figure out why the function returns the value that it does.
Function:
fun sum 0 = 0 | sum n = n+sum (n-1);
I understand that if the value of sum is 0, then 0 will be returned. However, I don't understand how the second part works.
Testing the function:
Input: sum 0; ---> output: 0;
Input: sum 1; ---> output: 1;
Input: sum 2; ---> output: 3;
Input: sum 3; ---> output: 6;
Input: sum 4; ---> output: 10;
I believe it should calculate such as: sum n = (n + (sum(n-1)), so given n = 2, (2 + (sum(2-1)) => 2 + 1 = 3;
But, given n = 4 , (4 + (sum(4-1)) => 4 + 3 = 7; I don't get the value that is outputed by the program.
If anyone could explain to me why or where I'm thinking wrong, that would be great help, thank you!