Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

howto catch a error when i do "read" on a list of integer?

Tags:

haskell

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?

like image 951
develhevel Avatar asked Jun 09 '11 06:06

develhevel


1 Answers

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> 
like image 142
n. 1.8e9-where's-my-share m. Avatar answered Oct 18 '22 03:10

n. 1.8e9-where's-my-share m.