Doubt, mistake Haskell

Asked

Viewed 107 times

0

I want to sum the values of a list of lists in Haskell using the map function, but of the error. Type error

gastoEmpresa :: [[Float]] -> Float
gastoEmpresa xss = map(map sum xss) 

inserir a descrição da imagem aqui

1 answer

0

The type of function map is

map :: (a -> b) -> [a] -> [b]

i and.., map is a function receives as parameters a function (from a for b) and a type list a and returns a type list b.

Knowing this, it is easy to understand the reason for the error message. In your second application, map takes fewer arguments/parameters than expected (map is Applied to Too few Arguments).

Let’s first remove the second application from the function map and see the partial result.

Be it l the list [[1, 4], [2, 3]], the result of map sum l is

[5, 5]

Thus, we were able to create a list in which each element results from the sum of the elements of the sub-lists. What we need now is not to apply the map function for the second time, but only a function that receives a list and returns the sum of all its elements: the function sum

Put it all together, one possible implementation would be:

gastoEmpresa :: [[Float]] -> Float
gastoEmpresa l = sum ( map sum l )

Or in the pointfree style:

gastoEmpresa :: [[Float]] -> Float
gastoEmpresa = sum . map sum

Browser other questions tagged

You are not signed in. Login or sign up in order to post.