空白敏感的FParsec

时间:2012-07-24 08:31:43

标签: f# fparsec

我正在尝试使用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"]

2 个答案:

答案 0 :(得分:3)

亲爱的,多么尴尬。

我想要sepEndBy,也就是说我应该终止分隔符上的解析。

答案 1 :(得分:0)

这看起来更惯用。我有硬编码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()