Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Map function – Couldn't match expected type `Int' with actual type `[a]'

this is an exercice :

-- Implement the function sumRights which sums all Right and discard Left
-- Examples:
--   sumRights [Right 1, Left "bad value", Right 2]  ==>  3
--   sumRights [Left "bad!", Left "missing"]         ==>  0

My idea was, as a first step, to transform the list with map into a list of integers only.
I wrote the following :

transformListToInt :: [Either a Int] -> Int
transformListToInt list = map f list
    where f (Right b) = b 
          f (Left  c) = 0
     

But it gives me the following error :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

* Couldn't match expected type `Int' with actual type `[a]'
* In the expression: map f list
  In an equation for `sumRights':
      sumRights list
        = map f list
        where
            f (Right b) = b
            f (Left c) = c

Could someone help me to understand why I get this error ?
(the initial problem is not so important, I could solve it differently)

>Solution :

You forgot to sum the list in the end:

transformListToInt :: [Either a Int] -> Int
transformListToInt list = sum $ map f list
    where f (Right b) = b 
          f (Left  c) = 0

A shorter way to write the same would be:

transformListToInt = sum . map (fromRight 0)

or even shorter:

transformListToInt = sum . rights

(both ways require importing Data.Either)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading