我尝试编写几个正确解析数字的函数,并进行所有检查(String -> Maybe a
某些集合的签名a
)。我已经编写了解析无界Integer
( maybeReadInteger
) 的函数,然后我想编写解析所有有界整数类型的多态函数:只需包含maybeReadInteger
一些范围检查。maybeReadNum
试图编写这样的函数,但它不进行类型检查。可以这样写吗?我必须打开哪些语言扩展(如果有)?
splitIntoSignAndDigits str = case str of
'-':rest -> (-1, rest)
'+':rest -> ( 1, rest)
_ -> ( 1, str )
maybeReadUnsignedInteger [] = Nothing
maybeReadUnsignedInteger str@(x:xs) = go 0 str
where go n str = case str of
[] -> Just n
(x:xs) | '0' <= x && x <= '9' -> go (10 * n + digit) xs
| otherwise -> Nothing
where digit = toInteger (ord x - ord '0')
maybeReadInteger str = fmap (sign*) (maybeReadUnsignedInteger str')
where (sign, str') = splitIntoSignAndDigits str
maybeReadNum :: (Integral a, Bounded a) => String -> Maybe a
maybeReadNum = fmap fromInteger .
mfilter (\n -> n >= toInteger (minBound :: a) &&
n <= toInteger (maxBound :: a)) .
maybeReadInteger
像这样的单态函数:
maybeReadInt :: String -> Maybe Int
maybeReadInt = fmap fromInteger .
mfilter (\n -> n >= toInteger (minBound :: Int) &&
n <= toInteger (maxBound :: Int)) .
maybeReadInteger
工作正常。