Jytug
Jytug

Reputation: 1116

Reading integers from a list

I'm facing the following problem in Haskell:

I want to parse such list: ["1", "2", "3"] into a Maybe [Int]. What I can do is, using readMaybe from Text.Read, is get a [Maybe Int] int the following way:

parseList :: [String] -> [Maybe Int]
parseList l = map readMaybe l :: [Maybe Int]

I could then do:

parseListMaybe :: [String] -> Maybe [Int]
parseListMaybe l = if (any isNothing parsed) then Nothing
                   else (Just $ catMaybes parsed)
                   where parsed = parseList l

But this doesn't seem to me like the most elegant and precise way to solve this. I would appreciate some hints on this

Upvotes: 2

Views: 147

Answers (1)

behzad.nouri
behzad.nouri

Reputation: 78011

use sequence from Control.Monad:

\> import Control.Monad (sequence)
\> import Text.Read (readMaybe)
\> sequence (readMaybe <$> ["1", "2", "3"]) :: Maybe [Int]
Just [1,2,3]
\> sequence (readMaybe <$> ["1", "xyz", "3"]) :: Maybe [Int]
Nothing

Upvotes: 3

Related Questions