Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elseif statement in Standard ML?

Tags:

sml

smlnj

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);
like image 364
jfisk Avatar asked Dec 13 '22 05:12

jfisk


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)
like image 154
pad Avatar answered Jan 21 '23 15:01

pad


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).

like image 37
Hunter McMillen Avatar answered Jan 21 '23 15:01

Hunter McMillen