1
votes

So I recently learned sml and really confused on how to use it compared to java. So I was told me make a code that takes consecutive pairs of values, adding them and inserting the sums into a new list.

If the original list has an odd length, then the first n-1 items are pairwise added, and the n-th item is simply copied as is at the end of the new list.

So my code so far is:

fun sumpairs x =

    if null x then []
    else (if (tl x =[]) then x
    else hd x + hd(tl x) :: sumpairs(tl (tl x));

sumpairs([1,2,3]); (I want to test it on this to get something like [3,3])

but I'm getting a syntax error. And since the sml doesn't find the error for me I'm lost on what the problem or if it even works or not. I believe that is should work.

1
Count your parentheses. I count one more opening parenthesis than closing. - sepp2k

1 Answers

5
votes

You have an unmatched parenthesis in (if (tl x =[]).
(SML's error messages are possibly the most confusing I've encountered - I get "syntax error at EOF", which is completely useless.)

It's easier to match parentheses if you use fewer:

fun sumpairs x =
    if null x then []
    else if tl x = [] then x
    else hd x + hd (tl x) :: sumpairs (tl (tl x))

An editor that can show which parentheses match also helps.
Most modern programmer's editors can do that, if you find the magic setting.

I would recommend that you get comfortable with pattern matching - it's usually much easier to follow the logic with patterns than with a chain of conditionals:

fun sumpairs [] = []
  | sumpairs [x] = [x]
  | sumpairs (x::y::xs) = x + y :: sumpairs xs