此代码将读取此输入“(WEEKEND-SUNDAY)”,然后返回“SATURDAY”
但输入 "WEEKEND-SUNDAY)"仍然返回 "SATURDAY"=> 这个解析器忽略最后一个 ')'
let pDayOfWeekKeyWords = choice [
pstring "MONDAY" ;
pstring "TUESDAY" ;
pstring "WEDNESDAY" ;
pstring "THURSDAY" ;
pstring "FRIDAY" ;
pstring "SATURDAY" ;
pstring "SUNDAY" ;
pstring "WEEKEND" ;
pstring "WEEKDAY" ;
pstring "ALL" ]
let betweenParentheses p =
between (pstring "(") (pstring ")") p
let opp = new OperatorPrecedenceParser<Set<DayOfWeek>,unit,unit>()
let pExpr = opp.ExpressionParser
let term = (betweenParentheses pExpr) <|> (pDayOfWeekKeyWords |>> ( fun x ->
match x with
| "MONDAY" -> Set.ofList [DayOfWeek.Monday]
| "TUESDAY" -> Set.ofList [DayOfWeek.Tuesday]
| "WEDNESDAY" -> Set.ofList [DayOfWeek.Wednesday]
| "THURSDAY" -> Set.ofList [DayOfWeek.Thursday]
| "FRIDAY" -> Set.ofList [DayOfWeek.Friday]
| "SATURDAY" -> Set.ofList [DayOfWeek.Saturday]
| "SUNDAY" -> Set.ofList [DayOfWeek.Sunday]
| "WEEKDAY" -> Set.ofList [DayOfWeek.Monday ; DayOfWeek.Tuesday ; DayOfWeek.Wednesday;DayOfWeek.Thursday;DayOfWeek.Friday]
| "WEEKEND" -> Set.ofList [DayOfWeek.Saturday;DayOfWeek.Sunday]
| "ALL"-> Set.ofList [DayOfWeek.Monday ; DayOfWeek.Tuesday ; DayOfWeek.Wednesday;DayOfWeek.Thursday;DayOfWeek.Friday;DayOfWeek.Saturday;DayOfWeek.Sunday]
| _ -> failwith "ERROR MESSAGE") )
opp.TermParser <- term
opp.AddOperator(InfixOperator<Set<DayOfWeek>,unit,unit>("+", skipString "", 1, Associativity.Left, fun x y -> x + y))
opp.AddOperator(InfixOperator<Set<DayOfWeek>,unit,unit>("-", skipString "" , 1, Associativity.Left, fun x y -> x - y))
运行
run pExpr "MONDAY+(WEEKEND-SUNDAY)"
输出
Success: set [Monday; Saturday]
问题是
run pExpr "MONDAY+WEEKEND-SUNDAY)" or run pExpr "MONDAY)+WEEKEND-SUNDAY"
它仍然返回
Success: set [Monday; Saturday]
我希望它显示失败:某事..
我错过了什么?谢谢你
最佳答案
在后两个示例中,pexpr
在成功解析输入流直到不匹配的右括号后返回。所以,在最后一个例子中,结果实际上是 Success: set [Monday]
而不是 Success: set [Monday; Saturday]
。
如果输入流没有被完全消耗,你可以使用 eof
解析器来强制错误:
> run (pExpr .>> eof) "MONDAY)+WEEKEND-SUNDAY"
Error in Ln: 1 Col: 7
MONDAY)+WEEKEND-SUNDAY
^
Expecting: end of input or infix operator
关于parsing - fparsec OperatorPrecedenceParser : How to deal with incomplete parentheses,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47901508/