我正在完成wikibooks /haskell上的练习,MonadPlus 章节中有一个练习,希望你编写这个 hexChar 函数。我的函数如下所示工作,但问题是当我尝试切换函数周围的 2 个帮助解析器(digitParse 和 alphaParse)时,它会停止正常工作。如果我切换它们,我只能解析数字而不是字母字符。
为什么会这样?
char :: Char -> String -> Maybe (Char, String)
char c s = do
let (c':s') = s
if c == c' then Just (c, s') else Nothing
digit :: Int -> String -> Maybe Int
digit i s | i > 9 || i < 0 = Nothing
| otherwise = do
let (c:_) = s
if read [c] == i then Just i else Nothing
hexChar :: String -> Maybe (Char, String)
hexChar s = alphaParse s `mplus` digitParse s -- cannot switch these to parsers around!!
where alphaParse s = msum $ map ($ s) (map char (['a'..'f'] ++ ['A'..'F']))
digitParse s = do let (c':s') = s
x <- msum $ map ($ s) (map digit [0..9])
return (intToDigit x, s')