我在玩 Haskell 的parsec庫。我試圖將形式的十六進制字串決議"#x[0-9A-Fa-f]*"為整數。這是我認為可行的代碼:
module Main where
import Control.Monad
import Numeric
import System.Environment
import Text.ParserCombinators.Parsec hiding (spaces)
parseHex :: Parser Integer
parseHex = do
string "#x"
x <- many1 hexDigit
return (fst (head (readHex x)))
testHex :: String -> String
testHex input = case parse parseHex "lisp" input of
Left err -> "Does not match " show err
Right val -> "Matched" show val
main :: IO ()
main = do
args <- getArgs
putStrLn (testHex (head args))
然后我嘗試testHex在 Haskell 的 repl 中測驗該函式:
GHCi, version 8.6.5: http://www.haskell.org/ghc/ :? for help
[1 of 1] Compiling Main ( src/Main.hs, interpreted )
Ok, one module loaded.
*Main> testHex "#xcafebeef"
"Matched3405692655"
*Main> testHex "#xnothx"
"Does not match \"lisp\" (line 1, column 3):\nunexpected \"n\"\nexpecting hexadecimal digit"
*Main> testHex "#xcafexbeef"
"Matched51966"
第一次和第二次嘗試按預期作業。但是在第三個中,字串匹配到無效字符。我不希望決議器這樣做,但如果字串中的任何數字不是有效字串,則不匹配。為什么會發生這種情況,如果解決這個問題怎么辦?
謝謝!
uj5u.com熱心網友回復:
你需要放在eof最后。
parseHex :: Parser Integer
parseHex = do
string "#x"
x <- many1 hexDigit
eof
return (fst (head (readHex x)))
或者,eof如果您想parseHex在其他地方重用,您可以將它與您使用它的地方組合在一起。
testHex :: String -> String
testHex input = case parse (parseHex <* eof) "lisp" input of
Left err -> "Does not match " show err
Right val -> "Matched" show val
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/314439.html
