Home > Enterprise >  Haskell sum a list with testcase
Haskell sum a list with testcase

Time:10-21

So I have the following code:

data List = Empty | Cons Integer List deriving Show

list = Cons 1 (Cons 7 (Cons 9 (Cons 3 Empty)))

Now I want to sum up the list created from above with this function:

-- sumList

sumList :: List -> Integer

sumList = sum

I do also have a testcase:

testSum = putStrLn ("expected: 20\ncomputed: "    show (sumList list))

My problem is, that I get the following error message:

Couldn't match typeList’ with ‘t0 Integer
  Expected type: List -> Integer
    Actual type: t0 Integer -> IntegerIn the expression: sum
  In an equation for ‘sumList’: sumList = sum

CodePudding user response:

data List = Empty | Cons Integer List deriving Show

sumList :: List -> Integer
sumList Empty = 0
sumList (Cons x xs) = x   sumList xs

As you can see, since List is a recursive data type, meaning it can hold instances of itself, we need to recursively open the members and add them all together.

As a test:

λ> list = Cons 1 (Cons 7 (Cons 9 (Cons 3 Empty)))
λ> sumList list
20

In your code, you are using sum from Data.Foldable. sum has the following signature:

λ> :t sum
sum :: (Foldable t, Num a) => t a -> a

This means that it needs a data type with an instance of the Foldable class to be able to work on, which List obviously does not have.

  • Related