Howto catch a bug when I do a “read” in a list of integers?

I need help, I need to read a list like this ["1", "2", "3"]and make a list of its integers [1,2,3], so I use read.

the problem is that when the list looks like the ["1", "2", "a"]program crashes due to an error in which there is a char.

How to check or throw an error to prevent this error?

+5
source share
1 answer

You should use reads, not read.

Prelude> :m Data.Maybe
Prelude Data.Maybe> (map (fmap fst . listToMaybe . reads) ["1", "2", "3"]) :: [Maybe Integer]
[Just 1,Just 2,Just 3]
Prelude Data.Maybe> (map (fmap fst . listToMaybe . reads) ["1", "2", "a"]) :: [Maybe Integer]
[Just 1,Just 2,Nothing]
Prelude Data.Maybe> 
+6
source

All Articles