[英]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
子句中返回Nothing
是個好主意嗎?
你可以用do
-notation和guard
從Control.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
好吧,如果您仍然要使用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
可能是意見和目標受眾的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.