【发布时间】:2017-01-01 13:45:01
【问题描述】:
我正在关注 this tutorial 在 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 的源代码对我来说是不可能的。
【问题讨论】:
-
这个简单的解析器库不需要
try。p <|> q的行为已经类似于try p <|> q。我说的对吗? -
好吧,
<|> :: Parser a -> Parser a -> Parser a需要一个替代我的 tried 选项。我希望能得到一些我可以try的东西,如果它失败了,什么也不做,然后在我的do符号中继续下一个语句。 -
<|>就是这样工作的。
标签: parsing haskell monads alternative-functor