FParsec样式;证明组合和monadic风格之间的差异?

时间:2012-04-05 19:45:12

标签: combinators fparsec

我是F#的新手,大约两个月,我最近完成了FParsec tutorial,并开始寻找更多的例子。我读的越多,我变得越困惑,然后我开始看到对样式的引用。我找了更多款式,想出了这份清单。

  • Combinator style
  • Monadic style
  • 箭头样式
  • 直接风格

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

“(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 and a delimiter based syntax

中的评论中选择了组合和monadic风格

直接样式始终显示为Direct Style Monadic Parser

箭头样式出现在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

1 个答案:

答案 0 :(得分:1)

Monadic style

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