Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (* Main.ml *)
- open Expressions
- let formula_of_string s = Parser.parse_expression Lexer.lex (Lexing.from_string s)
- let _ = print_endline (str (formula_of_string "a + b + g / c "))
- (* Parser.mly *)
- %token <string> VAR
- %token <int> CONST
- %token NEGATION ADDITION MULTIPLICATION DIVISION EOF
- %left ADDITION MULTIPLICATION DIVISION
- %right NEGATION
- %{
- open Expressions
- %}
- %start parse_expression
- %type <Expressions.term> parse_expression expression_expr
- %%
- %public expression_expr:
- | CONST { Const ($1) }
- | VAR { Var ($1) }
- | NEGATION expression_expr { Negation ($2) }
- | expression_expr ADDITION expression_expr { Addition ($1 , $3) }
- | expression_expr MULTIPLICATION expression_expr { Multiplication ($1 , $3) }
- | expression_expr DIVISION expression_expr { Division ($1 , $3) }
- parse_expression:
- | expression_expr EOF { $1 }
- (* Lexer.mll *)
- {
- open Parser
- }
- rule lex = parse
- | [' ' '\t'] { lex lexbuf }
- | ['0' - '9']+* {CONST}
- | ['A'-'Z' 'a'-'z']+* {VAR}
- | "-" {NEGATION}
- | "+" {ADDITION}
- | "*" {MULTIPLICATION}
- | "/" {DIVISION}
- | eof { EOF }
- (* Expressions.ml *)
- type term =
- | Const of int
- | Var of string
- | Negation of term
- | Addition of term * term
- | Multiplication of term * term
- | Division of term * term;;
- let rec str = function
- | Const cnst -> string_of_int cnst
- | Var v -> v
- | Negation n -> " -" ^ str n
- | Addition (hd , tl) -> (str hd) ^ " + " ^ (str tl)
- | Multiplication (hd , tl) -> (str hd) ^ " * " ^ (str tl)
- | Division (hd , tl) -> (str hd) ^ " / " ^ (str tl);;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement