i need help, i have to read a list like this ["1", "2", "3"] and make a list of integer of it [1,2,3] so i use read.

the problem is, when the list looks like ["1", "2", "a"] the programm quits because of the error that there is a char in it.

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

link|flag

1 Answer

You should be using 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> 
link|flag
1  
Note that this will happily turn "123abc" into 123. You need to also check that the second element of the tuple is empty to prevent this. – sepp2k 1 hour ago
@sepp2k Good call. – n.m. 3 mins ago

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.