1

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
  • 1
    Count your parentheses. I count one more opening parenthesis than closing. Commented Dec 6, 2017 at 4:10

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.