i wrote program in ocaml given infix expression 1 + 2, outputs prefix notation : + 1 2
my problem don't find way make rules : value, operator , bracket should separated @ least 1 space: 1+ 1 wrong 1 + 1 ok. not use ocamlp4 grammar.
here code:
open genlex type tree = | leaf of string | node of tree * string * tree let my_lexer str = let kwds = ["("; ")"; "+"; "-"; "*"; "/"] in make_lexer kwds (stream.of_string str) let make_tree_from_stream stream = let op_parser operator_l higher_perm = let rec aux left higher_perm = parser [<'kwd op when list.mem op operator_l; right = higher_perm; s >] -> aux (node (left, op, right)) higher_perm s | [< >] -> left in parser [< left = higher_perm; s >] -> aux left higher_perm s in let rec high_perm l = op_parser ["*"; "/"] brackets l , low_perm l = op_parser ["+"; "-"] high_perm l , brackets = parser | [< 'kwd "("; e = low_perm; 'kwd ")" >] -> e | [< 'ident n >] -> leaf n | [< 'int n >] -> leaf (string_of_int n) in low_perm stream let rec draw_tree = function | leaf n -> printf.printf "%s" n | node(fg, r, fd) -> printf.printf "(%s " (r); draw_tree fg; printf.printf " "; draw_tree fd; printf.printf ")" let () = let line = read_line() in draw_tree (make_tree_from_stream (my_lexer line)); printf.printf "\n"
plus if have tips code or if notice error of prog style appreciate let me know. !
the genlex
provides ready-made lexer respects ocaml's lexical convention, , in particular ignore spaces in positions mention. don't think can implement want on top of (it not designed flexible solution, quick way prototype working).
if want keep writing stream parsers, write own lexer it: define token
type, , lex char stream.t
token stream.t
, can parse wish. otherwise, if don't want use camlp4, may want try lr parser generator, such menhir (a better ocamlyacc).
Comments
Post a Comment