首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >区分空格的FParsec

区分空格的FParsec
EN

Stack Overflow用户
提问于 2012-07-24 16:31:43
回答 2查看 544关注 0票数 2

我正在尝试使用FParsec实现一个空格敏感的解析器,并从定义一个函数开始,这个函数将解析以空格的n字符开头的文本行。

这是我到目前为止所知道的:

代码语言:javascript
复制
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"]

EN

回答 2

Stack Overflow用户

发布于 2012-07-24 16:43:57

哦,天哪,真尴尬。

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

票数 3
EN

Stack Overflow用户

发布于 2012-07-25 20:20:35

这看起来更惯用。我有硬编码的1,但它很容易提取为参数。

代码语言:javascript
复制
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()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11627037

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档