【发布时间】:2018-06-02 03:13:18
【问题描述】:
下面的实际场景是虚构的。这个问题的目的是更多地了解 FParsec 在这里做了什么。
我正在解析由一个或多个空格字符 ' ' 分隔的字符串 (w) 和 (x) 的列表。
我的列表xs 的解析器使用sepBy 和分隔符解析器isSeparator。
isSeparator 基于manySatisfy 并且似乎正确地使用了空格。我相信当它解析两个在位置 3 结束的前导空格字符时,可以在下面的测试输出中看到这一点。
但是我在xs中使用它就失败了,如下图。
为什么会失败?处理可能是一个或多个空格的分隔符的好方法是什么?
open FParsec
let test p str =
match run p str with
| Success(result, _, p) -> printfn "Success: %A position = %A" result p
| Failure(errorMsg, _, _) -> printfn "Failure: %s" errorMsg
let str s = pstringCI s
let w = str "(w)"
let z = str "(z)"
let woz = w <|> z
let isSeparator = manySatisfy (fun c -> c = ' ')
let xs = sepBy woz isSeparator
test isSeparator " (w)" // Success: " " position = (Ln: 1, Col: 3)
test xs "(z) (w)" // Failure: Error in Ln: 1 Col: 8
// (z) (w)
// ^
// Note: The error occurred at the end of the input stream.
// Expecting: '(w)' (case-insensitive) or '(z)' (case-insensitive)
【问题讨论】:
-
我不太确定问题是什么。解析器
xs正确解析w或z由单个空格分隔,因为这是您指定为分隔符的内容。解析器x2应该可以按预期工作:解析w或z由多个空格分隔。 -
天哪 - 我的错...代码格式错误。将编辑和更新。谢谢 Fyodor Soikin。
-
现在已经编辑和更新了代码。