Deprecated: The each() function is deprecated. This message will be suppressed on further calls in /home/zhenxiangba/zhenxiangba.com/public_html/phproxy-improved-master/index.php on line 456
type token = End | TInt of int | TPlus | TMul | Lpar | Rpar type stream = { pos : int; buf : string } let stream_of_string buf = { pos = 0; buf = buf } exception Lexing_error of stream let next_token s = if s.pos = String.length s.buf then (End, s) else let next_stream size_token = { pos = s.pos + size_token; buf = s.buf } in match s.buf.[s.pos] with '0' .. '9' -> let rec read_int acc p = if p < String.length s.buf && s.buf.[p] >= '0' && s.buf.[p] <= '9' then read_int (acc * 10 + Char.code s.buf.[p] - Char.code '0') (p + 1) else (TInt acc, next_stream (p - s.pos)) in read_int 0 s.pos | '+' -> TPlus, next_stream 1 | '*' -> TMul, next_stream 1 | '(' -> Lpar, next_stream 1 | ')' -> Rpar, next_stream 1 | _ -> raise (Lexing_error s) let rec tokenize : stream -> token list = fun s -> match next_token s with End, _ -> [End] | t, s' -> t :: tokenize s' type expr = Int of int | Plus of expr * expr | Mul of expr * expr exception Syntax_error of stream let syntax_error s = raise (Syntax_error (s)) (* S -> T end T -> F | F + T F -> A | A * F A -> int | ( T ) *) let rec p_expr s = let t, s1 = p_terme s in match next_token s1 with End, _ -> t | _ -> syntax_error s and p_terme s = let f, s1 = p_facteur s in match next_token s1 with | TPlus, s2 -> let t, s3 = p_terme s2 in Plus (f, t), s3 | _ -> f, s1 and p_facteur s = let a, s1 = p_atome s in match next_token s1 with TMul, s2 -> let f, s3 = p_facteur s2 in Mul (a, f), s3 | _ -> a, s1 and p_atome s = match next_token s with TInt i, s1 -> Int i, s1 | Lpar, s1 -> let t, s2 = p_terme s1 in (match next_token s2 with Rpar, s3 -> t, s3 | _ -> syntax_error s2 ) | _ -> syntax_error s let expr_of_string s = p_expr (stream_of_string s) let string_of_expr_naif e = let rec soen e = match e with Int i -> string_of_int i | Plus (e1, e2) -> "(" ^ soen e1 ^ ")+(" ^ soen e2 ^ ")" | Mul (e1, e2) -> "(" ^ soen e1 ^ ")*(" ^ soen e2 ^ ")" in soen e let rec string_of_term e = match e with Plus (e1, e2) -> string_of_term e1 ^ "+" ^ string_of_term e2 | _ -> string_of_fact e and string_of_fact e = match e with Mul (e1, e2) -> string_of_fact e1 ^ "*" ^ string_of_fact e2 | _ -> string_of_atom e and string_of_atom e = match e with Int i -> string_of_int i | _ -> "(" ^ string_of_term e ^ ")" let string_of_expr e = string_of_term e (* let _ = expr_of_string "24*5+3" let _ = expr_of_string "24*5+3*4" let _ = expr_of_string "1*2+3" let _ = expr_of_string "1+2*3" let s = stream_of_string "24*5+3";; let x, s = next_token s;; *)