【问题标题】:Reading integers from a list从列表中读取整数
【发布时间】:2017-03-18 18:12:47
【问题描述】:

我在 Haskell 中遇到以下问题:

我想解析这样的列表: ["1", "2", "3"] 变成 Maybe [Int]。我能做的是,使用Text.Read 中的readMaybe,通过以下方式获得[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

但这在我看来并不是解决这个问题的最优雅和最精确的方法。我会很感激这方面的一些提示

【问题讨论】:

  • parseListMaybe = sequence . map readMaybe.
  • 或者更短 - traverse readMaybemapM readMaybe 如果你愿意的话

标签: haskell functional-programming


【解决方案1】:

使用来自Control.Monadsequence

\> 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

【讨论】:

    猜你喜欢
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 2013-07-06
    相关资源
    最近更新 更多