3
假設有一個數據結構代表裏面有註釋的文本。attoparsec中的條件性前瞻
data TWC
= T Text TWC -- text
| C Text TWC -- comment
| E -- end
deriving Show
因此字符串如
"Text, {-comment-}, and something else"
可以編碼爲
T "Text, " (C "comment" (T ", and something else" E))
解析器評論塊和E
是相當簡單:
twcP :: Parser TWC
twcP = eP <|> cP <|> tP
cP :: Parser TWC
cP = do
_ <- string "{-"
c <- manyTill anyChar (string "-}")
rest <- cP <|> tP <|> eP
return (C (pack c) rest)
eP :: Parser TWC
eP = do
endOfInput
return E
實施在這樣一個平凡的方式荷蘭國際集團的文本塊解析器
tP :: Parser TWC
tP = do
t <- many1 anyChar
rest <- cP <|> eP
return (T (pack t) rest)
使其消耗,因爲
> parseOnly twcP "text{-comment-}"
Right (T "text{-comment-}" E)
it ∷ Either String TWC
所以其貪婪的本性評論部分爲文本,問題是如何表達解析,直到邏輯輸入結束或直到評論部分?換句話說,如何實現有條件的超前解析器?