Search code examples
smlsmlnj

SML adding two pairs of numbers in a list


I'm trying to take a list, for example [1,2,3,4], and add each pair of in the list to get a new list [3,7]. I keep getting an error and I don't know what it means. Any help would be appreciated.

fun listsum x =
if null x then 0
else hd x + hd(tl x) :: listsum(tl x) + listsum(tl(tl x));

stdIn:3.6-3.58 Error: operator and operand don't agree [overload]

 operator domain: 'Z * 'Z list
  operand:         'Z * 'Y
  in expression:
    hd x + hd (tl x) :: listsum (tl x) + listsum (tl (tl <exp>))

Solution

  • There are two problems here: the first is that in the last line, you are asking for the sum of two lists with +; the second is that you are returning an int in one branch of the if, and a list in the other.

    The first problem just looks like a thinko: you've done all the addition you need in the left hand side of the ::, all that remains is to recurse over the rest of the list.

    Fixing both,

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