Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 1st, 2012  |  syntax: None  |  size: 1.48 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Parsing function application with FParsec using OperatorPrecedenceParser?
  2. type Expression =
  3.   | Float of float
  4.   | Variable of VarIdentifier
  5.   | BinaryOperation of Operator * Expression * Expression
  6.   | FunctionCall of VarIdentifier (*fun name*) * Expression list (*arguments*)
  7.        
  8. board→create_obstacle(4, 4, 450, 0, fric)
  9.        
  10. let expr = (number |>> Float) <|> (ident |>> Variable)
  11. let parenexpr = between (str_ws "(") (str_ws ")") expr
  12.  
  13. let opp = new OperatorPrecedenceParser<_,_,_>()
  14.  
  15. opp.TermParser <- expr <|> parenexpr
  16.  
  17. opp.AddOperator(InfixOperator("→", ws,
  18.   10, Associativity.Right,
  19.   fun left right -> BinaryOperation(Arrow, left, right)))
  20.        
  21. let primitive = expr <|> parenexpr
  22. let argList = sepBy primitive (str_ws ",")
  23. let fcall = tuple2 ident (between (str_ws "(") (str_ws ")") argList)
  24.        
  25. Success: Expression (BinaryOperation
  26.      (Arrow,Variable "board",Variable "create_obstacle"))
  27.        
  28. Success: Expression
  29.       (BinaryOperation
  30.             (Arrow,
  31.                 Variable "board",
  32.                 Function (VarIdentifier "create_obstacle",
  33.                           [Float 4, Float 4, Float 450, Float 0, Variable "fric"]))
  34.        
  35. let argListInParens = between (str_ws "(") (str_ws ")") argList
  36. let identWithOptArgs =
  37.     pipe2 ident (opt argListInParens)
  38.           (fun id optArgs -> match optArgs with
  39.                              | Some args -> FunctionCall(id, args)
  40.                              | None -> Variable(id))
  41.        
  42. let expr = (number |>> Float) <|> identWithOptArgs