1

Function should works like this:

sumFstElems [[1,2],[10,122,1],[12],[0],[1,1000]] = 24

I know that this prints first elements from lists:

fun xs = fmap head xs

This sum elements in list:

mysum (x:xs) = x + mysum xs

I have a problem with combining these two functions to give the expected result.

1
  • What should sumFstElems [[]] return? Commented Feb 20, 2022 at 1:00

2 Answers 2

1

This is how I would write the function:

sumFstElems :: [[Int]] -> Int
sumFstElems nss = sum (map head nss)

With fun and mysum it can be written as

sumFstElems :: [[Int]] -> Int
sumFstElems nss = mysum (fun nss)

or

sumFstElems :: [[Int]] -> Int
sumFstElems = mysum . fun
Sign up to request clarification or add additional context in comments.

Comments

1

Let's consider some basics:

Prelude> lst = [[1, 2], [6], [8, 9]]
Prelude> map head lst
[1,6,8]
Prelude> sum (map head lst)
15

Now, let's make a function:

Prelude> sumFstElems lst = sum (map head lst)
Prelude> sumFstElems lst
15

But what if we use . to compose the functions sum and map head, and then apply that to the lst argument?

Prelude> sumFstElems lst = (sum . map head) lst
Prelude> sumFstElems lst
15

That works. But then we don't need to explicitly list the argument.

Prelude> sumFstElems = sum . map head
Prelude> sumFstElems lst
15

Of course, this will fail if any of the lists contained in lst are empty. Given that this is possible, maybe we should filter those out.

Prelude> sumFstElems = sum . map head . filter (/= [])
Prelude> sumFstElems [[1, 2], [6], [8, 9], [], [4]]
19

A list comprehension provides a way of combining the filtering and mapping.

Prelude> sumFstElems lst = sum [head x | x <- lst, x /= []]
Prelude> sumFstElems [[1, 2], [6], [8, 9], [], [4]]
19

3 Comments

null :: Foldable t => t a -> Bool might fit well with your approach.
If you're going to do a list comprehension, use [x | x:_ <- lst]. This doesn't incur an Eq constraint (and is more concise to boot). I would suggest a similar technique to avoid (/=) in the filter version. The standard total alternative to head is take 1. So, sum . concatMap (take 1).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.