Links und Funktionen
Sprachumschaltung

Navigationspfad
Sie sind hier: Startseite / Lehre / SS 2011 / Programmierung und Modellierung / Lexer und Parser fuer arith Ausdr


Inhaltsbereich

Lexer und Parser fuer arith Ausdr

OCaml source code icon exp.ml — OCaml source code, 1 KB (1824 bytes)

Dateiinhalt

datatype token = ADD | MUL | LPAR | RPAR | XX | YY
exception error of string;
fun lex nil= nil
   |   lex (#" " :: cr) = lex cr
   |   lex (#"\t" :: cr) = lex cr
   |   lex (#"\n" :: cr) = lex cr
   |   lex (#"x" :: #"x" :: cr)= XX :: lex cr
   |   lex (#"y" :: #"y" :: cr)= YY :: lex cr
   |   lex (#"+" :: cr)= ADD :: lex cr
   |   lex (#"*" :: cr)= MUL :: lex cr
   |   lex (#"(" :: cr) = LPAR :: lex cr
   |   lex (#")" :: cr) = RPAR :: lex cr
   |   lex _ = raise error "lex";

datatype exp = Id of string | Sum of exp * exp | Pro of exp * exp 

fun 
      parseexp text = let val (tree,rest) = parsesummand text in 
                          case rest of 
                               ADD :: rest1 => let val (tree2,rest2) = 
                                            parseexp rest1 in
                                       (Sum(tree,tree2), rest2) end
                             | _ => (tree,rest)
                      end
and parsesummand text  = let val (tree,rest) = parsefaktor text in 
                          case rest of 
                               MUL :: rest1 => let val (tree2,rest2) = 
                                            parsesummand rest1 in
                                       (Pro(tree,tree2), rest2) end
                             | _ => (tree,rest)
                      end

and parsefaktor text = case text of 
                        XX::rest => (Id "xx",rest)
	              | YY::rest => (Id "yy",rest)
                      | LPAR :: rest => let val (tree,rest1) = parseexp rest in
                                 case rest1 of 
                                     RPAR :: rest2 => (tree,rest2)
                                   | _ => raise (error "parsepexp")
                                         end
                      | _ => raise (error "parsepexp")
 

Artikelaktionen


Funktionsleiste