我正在按照本教程在 Haskell 中实现 Parser Combinators (a la parsec)。我实现了这篇文章中提到的所有 NanoParsec。
几个小时以来,我正在努力实施
-- try p. If p fails continue without consuming anything
try :: Parser a -> Parser a
try p = ...
-- Parser for everything, until the character-sequence stop appears.
-- If stop does not appear at all: fail
untilStop :: String -> Parser String
untilStop stop = ...
我实现的最佳尝试untilStop
看起来有点像这样,但不太奏效
untilStop :: String -> Parser String
untilStop (c : cs) = do
s <- some $ satisfy (/= d)
string (c : cs) <|> do
i <- item
untilStop (d : ds)
-- maybe use msum from MonadPlus to combine?
我不知道如何组合s
,i
并且递归调用没有失败,因为string
没有把所有东西放在一起。
我想一旦我有了try
,untilStop
应该是直截了当的。有人可以为我指出正确的方向或实施它(try
)吗?
现在我还在学习 Monads、Applicative 和相关的东西,所以试图理解 parsec 的源代码对我来说是不可能的。