Search code examples
listsml

SML - Alternating Sum Using Pattern Matching


I'm writing a program that accepts a list of int and returns the value of their alternating sum.

Input: [1,2,3,4]
Output: 1 + (-2) + 3 + (-4)

Below is the code I tried to write for doing this, but I keep getting the error syntax error: inserting ORELSE

My if then else statement looks correct, so I'm not sure what could be causing the error

fun alternate([]) = 0
  | alternate(x::xs, count) = 
        count = count + 1
        if count mod 2 == 0 then (~x) + alternate(xs)
        else x + alternate(xs)

Solution

  • This error is caused by that count = count + 1 and if ... else ... are multiple expressions. If you want to execute multiple expressions, you can write the code like this:

    (expression1;
     expression2;
         ...
     expressionN);
    

    There are two other errors in your code.
    1. The parameters are not the same type in different pattern clauses of the function alternate.
    2. In SML = indicates equality, not ==.

    So a correct solution may look like this:

    fun alternate([]) = 0
      | alternate(x::xs) =
          let 
            fun alt([], count) = 0
              | alt(x::xs, count) =
                  if count mod 2 = 0 then x + alt(xs, count+1)
                  else (~x) + alt(xs, count+1)
          in 
            alt(x::xs, 0)
          end;