内部にコメントを含むテキストを表すデータ構造があるとします。
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))
コメント チャンクと for のパーサー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
では、問題は、入力の最後まで、またはコメント セクションまでの解析のロジックをどのように表現するかということです。つまり、条件付き先読みパーサーを実装する方法は?