Elseif Statement in Standard Ml?

Im doing a homework problem to make a function sumOdd to computer the sum of the first n odd integers, but i cant seem to find any sort of elseif type statement to do so. What im trying to do is below but of course doesnt work:

fun sumOdd n = if n=0 then 0 elseif (n mod 2)=0 then sumOdd(n-1) elseif n + sumOdd(n-1);
3

2 Answers

Your function didn't compile because elseif is not a keyword in SML. Changing the last elseif to else and other elseif to else if should fix the error.

Furthermore, the function is more readable in the below format:

fun sumOdd n = if n = 0 then 0 
               else if n mod 2 = 0 then sumOdd(n-1) 
               else n + sumOdd(n-1)

You could also remove the need for the else if expression by separating the base case from the general case:

fun sumOdd 0 = 0 
  | sumOdd n = if n mod 2 = 0 then sumOdd(n-1)
               else n + sumOdd(n-1)

You should also note that this solution does (and your own) does not actually sum the first N odd numbers. It computes the sum of all odd numbers less than N.

sumOdd(5) gives 9(5+3+1) when it should give 25(1+3+5+7+9).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest