我正在尝试使用FParsec实现一个空格敏感的解析器,并从定义一个函数开始,这个函数将解析以空格的n字符开头的文本行。
这是我到目前为止所知道的:
let test: Parser<string list,int>
= let manyNSatisfy i p = manyMinMaxSatisfy i i p
let p = fun (stream:CharStream<int>) ->
let state = stream.UserState
// Should fail softly if `state` chars wasn't parsed
let result = attempt <| manyNSatisfy state (System.Char.IsWhiteSpace) <| stream
if result.Status <> Ok
then result
else restOfLine false <| stream
sepBy p newline我的问题是当我跑的时候
runParserOnString test 1 "test" " hi\n there\nyou" |> printfn "%A"
我得到了一个关于“你”的错误。我的印象是,attempt会回溯任何状态更改,而将Error作为我的状态返回会导致软故障。
如何从解析器中取回["hi"; "there"]?
发布于 2012-07-24 16:43:57
哦,天哪,真尴尬。
我想要sepEndBy,也就是说我应该终止分隔符上的解析。
发布于 2012-07-25 20:20:35
这看起来更惯用。我有硬编码的1,但它很容易提取为参数。
let skipManyNSatisfy i = skipManyMinMaxSatisfy i i
let pMyText =
( // 1st rule
skipManyNSatisfy 1 System.Char.IsWhiteSpace // skip an arbitrary # of WhiteSpaces
>>. restOfLine false |>> Some // return the rest as Option
)
<|> // If the 1st rule failed...
( // 2nd rule
skipRestOfLine false // skip till the end of the line
>>. preturn None // no result
)
|> sepBy <| newline // Wrap both rules, separated by newLine
|>> Seq.choose id // Out of received string option seq, select only Some()https://stackoverflow.com/questions/11627037
复制相似问题