haskell - 当我期望看到失败时,为什么我看到 attoparsec 的部分结果?

标签 haskell attoparsec

我对 attoparsec 的这种行为有点困惑。

$ ghci
> :m Data.Attoparsec.Text
> :m + Data.Text
> parse (string (pack "module")) (pack "mox")
Partial _
> parse (string (pack "module")) (pack "moxxxx")
Fail "moxxxx" [] "Failed reading: takeWith"
> 

为什么我需要存在其他字符才能触发失败?

难道不应该在遇到第一个“x”时就失败吗?

最佳答案

这是一个实现细节,字符串解析器在知道是否有足够的剩余输入可能成功之前不会完成。这是这些解析器的全有或全无行为的结果(我认为这通常对性能有好处)。

string :: Text -> Parser Text
string s = takeWith (T.length s) (==s)

string s 尝试获取 Textlength s 个单位,然后与 s 进行比较。

takeWith :: Int -> (Text -> Bool) -> Parser Text
takeWith n p = do
  s <- ensure n
  let h = unsafeTake n s
      t = unsafeDrop n s
  if p h
    then put t >> return h
    else fail "takeWith"

takeWith n p 首先尝试确保 nText 单元可用,并且

ensure :: Int -> Parser Text
ensure !n = T.Parser $ \i0 a0 m0 kf ks ->
    if lengthAtLeast (unI i0) n
    then ks i0 a0 m0 (unI i0)
    else runParser (demandInput >> go n) i0 a0 m0 kf ks
  where
    go n' = T.Parser $ \i0 a0 m0 kf ks ->
        if lengthAtLeast (unI i0) n'
        then ks i0 a0 m0 (unI i0)
        else runParser (demandInput >> go n') i0 a0 m0 kf ks

ensure n 如果没有立即找到足够的输入,则会创建一个延续,要求更多的gruel 输入(部分 结果)。

你可能会失败

Prelude Data.Attoparsec.Text Data.Text> parseOnly (string (pack "module")) (pack "mox")
Left "not enough input"

预先告诉解析器它将不再获得任何输入(然后来自 ensuredemandInput 使其失败),或稍后

Prelude Data.Attoparsec.Text Data.Text> parse (string (pack "module")) (pack "mox")
Partial _
Prelude Data.Attoparsec.Text Data.Text> feed it (pack "")
Fail "mox" ["demandInput"] "not enough input"

通过告诉 Partial 结果就是这样,并为其提供一个空的Text

关于haskell - 当我期望看到失败时,为什么我看到 attoparsec 的部分结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14287237/

相关文章:

Haskell:Where 与 Let

haskell - 空列表测试中的歧义类型变量

haskell - Attoparsec 支持保存和修改用户状态吗?

haskell - 了解 attoparsec 实现(第 2 部分)

parsing - Haskell 中的句柄增量解析

haskell - 有没有更好的方法来编写indexof函数?

haskell - 有没有办法直接引用 Haskell 中的类型类实例?

haskell - 如何规避 Haskell 中的现有实例(失败)?

performance - 有效地将大文件读入 map

parsing - 使用 attoparsec 对解析后的数据进行操作