[英]I don't understand how to use the lexeme function
從Text.Parsec.Token
:
lexeme p = do { x <- p; whiteSpace; return x }
lexeme看起來采用了解析器p並提供了與p具有相同行為的解析器,除了它還跳過了所有尾隨空白。 正確?
然后,下面的方法不起作用:
constant :: Parser Int
constant = do
digits <- many1 digit
return (read digits)
lexConst :: Parser Int
lexConst = lexeme constant
最后一行導致以下錯誤消息:
Couldn't match expected type `ParsecT
String () Data.Functor.Identity.Identity Int'
with actual type `ParsecT s0 u0 m0 a0 -> ParsecT s0 u0 m0 a0'
Expected type: Parser Int
Actual type: ParsecT s0 u0 m0 a0 -> ParsecT s0 u0 m0 a0
In the return type of a call of `lexeme'
In the expression: lexeme constant
我究竟做錯了什么?
您誤解了文檔,從Text.Parsec.Token
導出的lexeme
是GenTokenParser sum
的字段,因此類型為
lexeme :: GenTokenParser s u m -> ParsecT s u m a -> ParsecT s u m a
並且您還沒有在lexeme constant
提供GenTokenParser
參數。
您需要GenTokenParser
從GenLanguageDef
(通常與makeTokenParser
)一起創建GenTokenParser
,才能使用其lexeme
字段。
的lexeme
功能是訪問到GenTokenParser
所產生的解析器的記錄makeTokenParser
,所以你需要將它應用到這樣的記錄得到它。 一種常用的方法是使用記錄通配符,例如
{-# LANGUAGE RecordWildCards #-}
import qualified Text.Parsec.Token as Tok
Tok.TokenParser { .. } = Tok.makeTokenParser {- language definition -}
這將使lexeme
和所有其他解析器進入已應用於記錄的范圍,因此您可以像嘗試使用它一樣使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.