Advertisement
Guest User

Untitled

a guest
Jun 18th, 2016
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.68 KB | None | 0 0
  1. (* Main.ml *)
  2. open Expressions
  3.  
  4. let formula_of_string s = Parser.parse_expression Lexer.lex (Lexing.from_string s)
  5.  
  6. let _ = print_endline (str (formula_of_string "a + b + g / c "))
  7.  
  8.  
  9. (* Parser.mly *)
  10.  
  11. %token <string> VAR
  12. %token <int>    CONST
  13. %token NEGATION ADDITION MULTIPLICATION DIVISION EOF
  14.  
  15. %left ADDITION MULTIPLICATION DIVISION
  16. %right NEGATION
  17.  
  18.  
  19. %{
  20.   open Expressions
  21. %}
  22.  
  23. %start parse_expression
  24. %type <Expressions.term> parse_expression expression_expr
  25.  
  26. %%
  27.  
  28. %public expression_expr:
  29.     | CONST { Const ($1) }
  30.     | VAR   { Var ($1) }
  31.     | NEGATION expression_expr      { Negation ($2) }
  32.     | expression_expr ADDITION expression_expr      { Addition ($1 , $3) }
  33.     | expression_expr MULTIPLICATION expression_expr        { Multiplication ($1 , $3) }
  34.     | expression_expr DIVISION expression_expr      { Division ($1 , $3) }
  35.  
  36.  
  37. parse_expression:
  38. | expression_expr EOF                      { $1 }
  39.  
  40.  
  41. (* Lexer.mll *)
  42. {
  43. open Parser
  44. }
  45.  
  46. rule lex = parse
  47.         | [' ' '\t']      { lex lexbuf }
  48.     | ['0' - '9']+*             {CONST}
  49.     | ['A'-'Z' 'a'-'z']+*               {VAR}
  50.     | "-"                   {NEGATION}
  51.     | "+"                   {ADDITION}
  52.     | "*"                   {MULTIPLICATION}
  53.     | "/"                   {DIVISION}
  54.     | eof                                   { EOF }
  55.  
  56.  
  57.  
  58. (* Expressions.ml *)
  59.  
  60. type  term =
  61.     | Const of int
  62.     | Var of string
  63.     | Negation of  term
  64.     | Addition of term *  term
  65.     | Multiplication of term * term
  66.     | Division of term * term;;
  67.  
  68. let rec str = function
  69.     | Const cnst -> string_of_int cnst
  70.     | Var v -> v
  71.     | Negation n -> " -" ^ str n
  72.     | Addition (hd , tl) -> (str hd) ^ " + " ^ (str tl)
  73.     | Multiplication (hd , tl) -> (str hd) ^ " * " ^ (str tl)
  74.     | Division  (hd , tl) -> (str hd) ^ " / " ^ (str tl);;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement