2

作为 trifecta 的实验,我编写了以下简单函数:

filterParser :: (a -> Bool) -> Parser a -> Parser a
filterParser cond p = do
  a <- p
  if cond a 
    then return a 
    else unexpected "condition failed!"

这个想法是能够向解析器添加条件。例如(假设谓词prime已经存在),您可以编写: filterParser prime integer创建一个只接受素数的解析器。


使用单次解析似乎没问题:

> parseString (filterParser (> 'm') letter) mempty "z"
> Success 'z

> parseString (filterParser (> 'm') letter) mempty "a"
> Failure (interactive):1:2: error: unexpected
> condition failed!

但是对于“很多”它不起作用 - 比较:

> parseString (many $ filterParser (> 'm') letter) mempty "zzz2"
> Success "zzz"

> parseString (many $ filterParser (> 'm') letter) mempty "zzza"
> Failure (interactive):1:5: error: unexpected
> condition failed!

我希望最后一个例子也能返回Success "zzz"。调用unexpected似乎使整个解析脱轨,这不是我想要的。

4

2 回答 2

1

除了 Cactus 提出的解决方案外,还有以下几种:


filterParser :: (a -> Bool) -> Parser a -> Parser a
filterParser cond p = do
  a <- lookAhead p
  if cond a then p else unexpected "condition failed!"

这似乎给了我想要的东西:

> parseString (filterParser (> 'm') letter) mempty "z"
> Success 'z'

> parseString (filterParser (> 'm') letter) mempty "4"
> Failure (interactive):1:1: error: expected: letter

> parseString (filterParser (> 'm') letter) mempty "a"
> Failure (interactive):1:1: error: unexpected
>     condition failed!

> parseString (many $ filterParser (> 'm') letter) mempty "zzz4"
> Success "zzz"

> parseString (many $ filterParser (> 'm') letter) mempty "zzza"
> Success "zzz"
于 2016-03-22T14:41:00.983 回答
1

您需要filterParser使用以下方法进行恢复try

import Text.Trifecta
import Control.Applicative

filterParser :: (a -> Bool) -> Parser a -> Parser a
filterParser cond p = try $ do
  x <- p
  if cond x then return x else empty

但是,这将消除自定义解析错误。通过unexpected "Condition failed"else分支中使用来恢复它也无济于事,因为try.

相反,我们可以在之后恢复自定义错误消息try

filterParser :: (a -> Bool) -> Parser a -> Parser a
filterParser cond p = (<|> unexpected "Condition failed") $ try $ do
  x <- p
  if cond x then return x else empty

这按预期工作:

*Main> parseString (many $ filterParser (> 'm') letter) mempty "zzza"
Success "zzz"

*Main> parseString (filterParser (> 'm') letter) mempty "a"
Failure (interactive):1:1: error: unexpected
    Condition failed
a<EOF> 
于 2016-03-22T06:09:34.297 回答