我在Haskell面临以下问题:
我想解析这样的列表:
["1", "2", "3"]
成Maybe [Int]
。我可以做的是,使用readMaybe
中的Text.Read
,以下列方式获取[Maybe Int]
int:
parseList :: [String] -> [Maybe Int]
parseList l = map readMaybe l :: [Maybe Int]
然后我可以这样做:
parseListMaybe :: [String] -> Maybe [Int]
parseListMaybe l = if (any isNothing parsed) then Nothing
else (Just $ catMaybes parsed)
where parsed = parseList l
但在我看来,这并不是解决这个问题最优雅,最精确的方法。我会很感激这个
的一些提示答案 0 :(得分:3)
使用Control.Monad
中的sequence
:
\> 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