我正在尝试创建一个验证输入String -> Maybe Int
的函数。我检查输入字符串是否是数字然后检查该数字是否在一个范围内。到目前为止我已经
validateNumber :: String -> Maybe Int
validateNumber n = go $ (readMaybe::String -> Maybe Int) n
where
go (Just a) = inRange a
go Nothing = Nothing
inRange :: Int -> Maybe Int
inRange n
| n > 0 = Just n
| otherwise = Nothing
这感觉就像糟糕的代码。该怎么写?
另外,如果我试图循环一个函数,如果它返回Nothing
,那么最好的方法是什么:
所以要循环main
函数,我正在做:
case v of
Nothing -> main
Just x -> {do something}
答案 0 :(得分:14)
您可以使用mfilter
过滤Maybe
范围内的超出范围的值,而不是明确匹配:
import Control.Monad (mfilter)
validateNumber :: String -> Maybe Int
validateNumber = mfilter (> 0) . readMaybe
答案 1 :(得分:8)
这个怎么样?
validateNumber :: String -> Maybe Int
validateNumber n = (readMaybe n) >>= inRange
甚至这个:
validateNumber :: String -> Maybe Int
validateNumber str = do
n <- readMaybe str
if n < 0 then Nothing else return n
(避免需要单独的inRange
功能。)
答案 2 :(得分:0)
我会尝试这样的事情(未经测试):
validateNumber :: String -> Maybe Int
validateNumber n = case (readMaybe::String -> Maybe Int) n of
(Just a) -> case n > 0 of
True -> Just n
False -> Nothing
Nothing -> Nothing
它有点短,更简洁。