使用 readMaybe 读取自然数列表

Using readMaybe to read list of natural numbers

我正在使用此函数以下列格式从字符串中读取自然数列表:[1, 2, 3]:

readMaybeIntList :: String -> Maybe [Int]
readMaybeIntList line = case readMaybe line of
                          Just l -> return l
                          Nothing -> Nothing

现在它只适用于整数 - 检查数字是否自然的正确方法是什么?我是否应该修改 Just l 子句以检查是否所有数字都是 >=0?从这样的嵌套 Just 子句中 return Nothing 是个好主意吗?

您可以使用 do 符号和 Control.Monad 中的 guard 来避免过多的模式匹配:

import Text.Read
import Control.Monad


readMaybeNatural :: String -> Maybe Int
readMaybeNatural str = do
  n <- readMaybe str
  guard $ n >= 0
  return n


readMaybeNaturals :: String -> Maybe [Int]
readMaybeNaturals =
  sequence . map readMaybeNatural . words

好吧,如果你打算使用 return 来调用 Maybe 的 monad 实例,那么我想我可能会写:

import Text.Read
import Control.Monad

readMaybeNatList :: String -> Maybe [Int]
readMaybeNatList line = do
  ns <- readMaybe line
  guard $ all (>=0) ns
  return ns

这是 Maybe monad 的更惯用的应用。它是否比显式模式匹配(和无 monad)替代方案更清晰:

readMaybeNatList' :: String -> Maybe [Int]
readMaybeNatList' line =
  case readMaybe line of
    Just ns | all (>=0) ns -> Just ns
    _ -> Nothing

可能是意见和目标受众的问题。