2

我是 F# 的新手,大约两个月,我最近完成了FParsec 教程并开始寻找更多示例。我读得越多,我就越困惑,然后我开始看到对样式的引用。我寻找更多样式并想出了这个列表。

  • 组合器风格
  • 单子风格
  • 箭头样式
  • 直接风格

有人可以列出所有样式并解释和演示每种样式如何解决常见问题,例如解析

“(abc 
  (b CDEF 
   (de 1 E) 
   (f 234)
  ) 
  (h 3) 
  (jkl H) 
 )”  

进入

[Lower "abc";
 Group[Lower "b"; Upper "CDEF"; 
  Group [Lower "de"; Number "1"; Upper "E"];
  Group [Lower "f"; Number "234"]]; 
 Group [Lower "h"; Number "3"];
 Group [Lower "jkl"; Upper "H"]
]

使用

Type out = 
| Lower of string
| Upper of string
| Number of string
| Group of out list

编辑

我从FParsec 中的注释和基于分隔符的语法中选择了组合子和单子样式

直接样式始终显示为直接样式单子解析器

箭头样式出现在Parsec: Direct Style Monadic Parser Combinators For The Real World我还没有阅读所有这些。

编辑

根据建议

组合器风格

type out =
| Lower of string
| Upper of string
| Number of string
| Group of out list

type Parser = Parser<out, unit>

let isUpper = fun c -> isAsciiUpper c 
let upper : Parser = 
    many1Satisfy isUpper .>> ws 
    |>> fun x -> Upper(x)

let isLower = fun c -> isAsciiLower c 
let lower : Parser= 
    many1Satisfy isLower .>> ws
    |>> fun x -> Lower(x)

let isNumber = fun c -> isDigit c 
let number : Parser =
    many1Satisfy isNumber .>> ws
    |>> fun x -> Number(x)

let groupRef, groupImpl = createParserForwardedToRef()

let item : Parser = 
    lower <|> upper <|> number <|> groupRef

let items = 
    many item .>> ws 
    |>> fun x -> Group(x)

do groupImpl := between (pchar '(') (pchar ')') items .>> ws 

let test () =
    match run groupRef "(abc (b CDEF (de 1 E) (f 234)) (h 3) (jkl H) )" with
    | Success(result, _, _)   -> printf "Success: %A" result
    | Failure(errorMsg, _, _) -> printf "Failure: %s" errorMsg
4

1 回答 1

1

单子风格

type out =
| Lower of string
| Upper of string
| Number of string
| Group of out list

type Parser = Parser<out, unit>

let isUpper = fun c -> isAsciiUpper c 
let upper : Parser =  parse {
    let! x = many1Satisfy isUpper 
    do! ws 
    return Upper(x)
    }

let isLower = fun c -> isAsciiLower c 
let lower = parse {
    let! x = many1Satisfy isLower
    do! ws 
    return Lower(x)
    }

let isNumber = fun c -> isDigit c 
let number = parse {
    let! x = many1Satisfy isNumber
    do! ws 
    return Number(x)
    }

let groupRef, groupImpl = createParserForwardedToRef()

let group =  parse {
    let! x = groupRef
    do! ws
    return x
    }

let item  = 
    lower <|> upper <|> number <|> group

let items = parse {
    let! x = many item   
    do! ws        
    return Group(x)
    }

do groupImpl := between (pchar '(') (pchar ')') items

let test () =
    match run group "(abc (b CDEF (de 1 E) (f 234)) (h 3) (jkl H) )" with
    | Success(result, _, _)   -> printf "Success: %A" result
    | Failure(errorMsg, _, _) -> printf "Failure: %s" errorMsg
于 2012-04-16T01:17:46.353 回答