jfisk
jfisk

Reputation: 6205

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

Upvotes: 4

Views: 26880

Answers (2)

Hunter McMillen
Hunter McMillen

Reputation: 61512

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

Upvotes: 1

pad
pad

Reputation: 41290

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)

Upvotes: 13

Related Questions