我有以下代码:
import Text.ParserCombinators.Parsec
import Control.Applicative hiding ((<|>))
import Control.Monad
data Test = Test Integer Integer deriving Show
integer :: Parser Integer
integer = rd <$> many1 digit
where rd = read :: String -> Integer
testParser :: Parser Test
testParser = do
a <- integer
char ','
b <- integer
eol
return $ Test a b
eol :: Parser Char
eol = char '\n'
main = forever $ do putStrLn "Enter the value you need to parse: "
input <- getLine
parseTest testParser input
但是当我真正尝试解析
ghci
中的值时,它不起作用。
ghci > main
Enter the value you need to parse:
34,343\n
parse error at (line 1, column 7):
unexpected "\\"
expecting digit or "\n"
关于我在这里缺少什么有什么想法吗?
问题似乎是您期待换行符,但您的文本不包含换行符。将
eol
更改为
import Control.Monad (void)
eol :: Parser ()
eol = void (char '\n') <|> eof
它会起作用的。
”
" 是 Haskell(和 C 等)字符串和字符文字中使用的转义码,用于表示 ASCII 0x0A,该字符用于在 UNIX 和类 UNIX 平台上指示行结束符。你不(通常) )使用键盘上的 <\> 或
在 PC-DOS 和类 DOS 系统上,ASCII 0x0D 后跟 ASCII 0x0A 用于行尾和“ " 是用于 ASCII 0x0D 的转义码。
getLine 读取直到找到行尾并返回一个包含除行尾字符之外的所有内容的字符串。因此,在您的示例中,您的解析器将无法匹配。您可以通过可选地匹配行尾来解决此问题。