我对 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
尝试获取 Text
的 length 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
首先尝试确保 n
个 Text
单元可用,并且
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"
预先告诉解析器它将不再获得任何输入(然后来自 ensure
的 demandInput
使其失败),或稍后
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/