algorithm – Haskell – Sum up the first n elements of a list

algorithm – Haskell – Sum up the first n elements of a list

So you know how to sum up the numbers in a list,

sumList :: [Int] -> Int
sumList [] = 0
sumList (x:xs) = x + sumList xs

and if that list has no more than 5 elements in it, this function will even return the correct result if you indeed intended to sum no more than 5 elements in an argument list. Lets make our expectations explicit by renaming this function,

sumUpToFiveElements :: [Int] -> Int
sumUpToFiveElements [] = 0
sumUpToFiveElements (x:xs) = x + sumUpToFiveElements xs

it wont return the correct result for lists longer than five, but at least the name is right.

Can we fix that? Can we count up to 5? Can we count up to 5 while also advancing along the input list as we do?

sumUpToFiveElements :: Int -> [Int] -> Int
sumUpToFiveElements counter [] = 0
sumUpToFiveElements counter (x:xs) = x + sumUpToFiveElements (counter + 1) xs

This still isnt right of course. We do now count, but for some reason we ignore the counter. What is the right time to react to the counter, if we want no more than 5 elements? Lets try counter == 5:

sumUpToFiveElements :: Int -> [Int] -> Int
sumUpToFiveElements 5       [] = 0
sumUpToFiveElements counter [] = 0
sumUpToFiveElements counter (x:xs) = x + sumUpToFiveElements (counter + 1) xs

But why do we demand the list to also be empty when 5 is reached? Lets not do that:

sumUpToFiveElements :: Int -> [Int] -> Int
sumUpToFiveElements 5       _  = 0        -- the wildcard `_` matches *anything*
sumUpToFiveElements counter [] = 0
sumUpToFiveElements counter (x:xs) = x + sumUpToFiveElements (counter + 1) xs

Success! We now stop counting when 5 is reached! More, we also stop the summation!!

Wait, but what was the initial value of counter? We didnt specify it, so its easy for a user of our function (that would be ourselves) to err and use an incorrect initial value. And by the way, what is the correct initial value?

Okay, so lets do this:

sumUpToFiveElements :: [Int] -> Int
sumUpToFiveElements xs = go 1 xs     -- is 1 the correct value here?
  where
    go counter  _ | counter == 5 = 0  
    go counter [] = 0
    go counter (x:xs) = x + go (counter + 1) xs

Now we dont have that extraneous argument that made our definition so brittle, so prone to a user error.

And now for the punchline:

Generalize! (by replacing an example value with a symbolic one; changing 5 to n).

sumUpToNElements :: Int -> [Int] -> Int
sumUpToNElements n xs = .......
   ........

Done.


One more word of advice: dont use $ while at the very beginning of your learning Haskell. Use explicit parens.

sumList take (x:xs) = x + take $ sumList xs 

is parsed as

sumList take (x:xs) = (x + take) (sumList xs)

This adds together two unrelated numbers, and then uses the result as a function to be called with (sumList xs) as an argument (in other words its an error).

You probably wouldnt write it that way if you were using explicit parens.

Well you should limit the number of values with a parameter (preferably not take, since
that is a function from the Prelude), and thus limit the numbers.

This limiting in your code is apparently take $ sumList xs which is very strange: in your function take is an Int, and $ will basically write your statement to (x + take) (sumList xs). You thus apparently want to perform a function application with (x + take) (an Int) as function, and sumList xs as argument. But an Int is not a function, so it does not typecheck, nor does it include any logic to limit the numbers.

So basically we should consider three cases:

  1. the empty list in which case the sum is 0;
  2. the number of elements to take is less than or equal to zero, in that case the sum is 0; and
  3. the number of elements to take is greater than 0, in that case we add the head to the sum of taking one element less from the tail.

So a straightforward mapping is:

sumTakeList :: (Integral i, Num n) => i -> [n] -> n
sumTakeList _ [] = 0
sumTakeList t (x:xs) | t <= 0 = 0
                     | otherwise = x + sumTakeList (t-1) xs

But you do not need to write such logic yourself, you can combine the take :: Int -> [a] -> [a] builtin with the sum :: Num a => [a] -> a functions:

sumTakeList  :: Num n => Int -> [n] -> n
sumTakeList t = sum . take t

Now if you need to sum the first five elements, we can make that a special case:

subList5 :: Num n => [n] -> n
sumList5 = sumTakeList 5

algorithm – Haskell – Sum up the first n elements of a list

A great resource to see what functions are available and how they work is Hoogle. Here is its page on take and the documentation for the function you want.

As you can see, the name take is taken, but it is a function you can use to implement this.

Note that your sumList needs another argument, the number of elements to sum. the syntax you want is something like:

sumList :: Int -> [Int] -> Int
sumList n xs = _ $ take n xs

Where the _ are blanks you can fill in yourself. Its a function in the Prelude, but the type signature is a little too complicated to get into right now.

Or you could write it recursively, with two base cases and a third accumulating parameter (by means of a helper function):

sumList :: Int -> [Int] -> Int
sumList n xs = sumList n xs 0 where
  sumList :: Int -> [Int] -> Int -> Int
  sumList 0 _ a = _ -- A base case.
  sumList _ [] a = _ -- The other base case.
  sumList m (y:ys) a = sumList _ _ _ -- The recursive case.

Here, the _ symbols on the left of the equals signs should stay there, and mean that the pattern guard ignores that parameter, but the _ symbols on the right are blanks for you to fill in yourself. Again, GHC will tell you the type you need to fill the holes with.

This kind of tail-recursive function is a very common pattern in Haskell; you want to make sure that each recursive call brings you one step closer to the base case. Often, that will mean calling itself with 1 subtracted from a count parameter, or calling itself with the tail of the list parameter as the new list parameter. here, you want to do both. Dont forget to update your running sum, a, when you have the function call itself recursively.

Leave a Reply

Your email address will not be published.