0

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!

Chris
  • 785
  • 10
  • 24

1 Answers1

1

When the program says sum(3) it does not mean add 3, it means add all the numbers up to and including 3 i.e. 0+1+2+3 = 6

I have no idea what SML NJ is, but here is my explaination -

The | operator says to me, "Evaluate the first expression sum 0 = 0. IF it is false, evaluate the second".

When you want the sum of first "0" integers, it just returns 0. Any thing over that it evaluates the second part of that expression.

Example

  1. Sum of first 0 integers is 0.
  2. Sum of first 1 integer is (sum of first 0 integers, i.e. 0) + (1 itself) = 1
  3. Sum of first 2 integers is (sum of first 1 integers, i.e. 1) + (2 itself) = 3
  4. And so on ...

The sum of first n numbers is n + sumOfFirst(n-1) UNLESS n=0 in which case it's just 0, so don't bother with recursion. Does that make sense?

Hope that helps!

Prashant
  • 1,002
  • 13
  • 29