简体   繁体   English

使用readMaybe读取自然数列表

[英]Using readMaybe to read list of natural numbers

I am using this function to read list of natural numbers from string in the following format: [1, 2, 3] : 我正在使用此函数以以下格式从字符串中读取自然数列表: [1, 2, 3]

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

Right now it only works for integers - what would be the correct way to check whether the numbers are natural? 现在,它仅适用于整数-检查数字是否自然的正确方法是什么? Should I modify the Just l clause to check whether all numbers are >=0 ? 我是否应该修改Just l子句以检查所有数字是否均>=0 Is it a good idea to return Nothing from such nested Just clause? 从嵌套的Just子句中返回Nothing是个好主意吗?

You could use do -notation and guard from Control.Monad to avoid the excessive pattern matching: 你可以用do -notation和guardControl.Monad避免过度模式匹配:

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

Well, if you're going to use return anyway to invoke the monad instance for Maybe , then I think I'd probably write: 好吧,如果您仍然要使用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

which is a more idiomatic application of the Maybe monad. 这是Maybe monad的惯用用法。 Whether it's clearer than the explicit pattern-matching (and monad-free) alternative: 是否比显式模式匹配(和无monad)更清晰:

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

is probably a matter of opinion and intended audience. 可能是意见和目标受众的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM