Plai-type's parser, have to say that Lisp is still good at dealing with parentheses expression, and its list of member allow different types, but really, still do not like Lisp.
#lang plai-typed (Define-type arithc [NUMC (N:number)] [PLUSC (L:ARITHC) (R:ARITHC)] [MULTC (L:ARITHC) (R:ARITHC)]) (Define (parse [s:s-expression]): arithc (Cond [(S-exp-number s) (NUMC (S-exp->number s))] [(s-exp-list? s) (Let ([SL (S-exp->list s)]) (Case (S-exp->symbol (first SL)) [(+) (PLUSC (Parse (second SL)) (Parse (third SL))] [(*) (MULTC (Parse (second SL)) (Parse (third SL))] [Else (Error ' Parse ' invalid list input ')])] [Else (Error ' Parse ' invalid input ')])) (Parse ' (+ (* 1 2) (+ 2 3)))
Because just started to learn OCaml, so also write a parser with OCaml, but I use the state machine to achieve, very ugly, verbose, and feel the code style or imperative, away from the functional or there is a great distance.
Let S = "(+ (* 1 2) (+ 2 3)" Inlet L = string.length s inlet state:int ref = ref 0 Inlet Rec Parse (i:int) = if I >= L then () Else (match S.[i] with | ' (' Print_char ' ('; If!state = 0 Then (state: = 1; Parse (i+1); ) Else If!state = 3 | | !state = 5 Then (state: = 1; Parse (i+1); ) Else (print_string "error"; Parse (i+1); ) | ' + ' if!state = 1 then (print_string "PLUSC"; state: = 2; Parse (i+1); ) Else (print_string "error"; Parse (i+1); ) | ' * ', if!state = 1 then (print_string "MULTC"; state: = 2; Parse (i+1); ) Else (print_string "error"; Parse (i+1); ) | "Print_char"; If!state = 2 Then (state: = 3; Parse (i+1); ) Else If!state = 4 | | !state = 7 Then (state: = 5; Parse (i+1); ) Else (print_string "error"; Parse (i+1); ) | ') ', Print_char '; If!state = 7 then (state: = 7; Parse (i+1); else if!state = 6 then (state: = 7; Parse (i+1); ) Else (print_string "error"; Parse (i+1); ) | C-Printf.printf "(NUMC%c)" C; If!state = 3 then (state: = 4; Parse (i+1); else if!state = 1 then (state: = 8; Parse (i+1); else if!state = 5 then (state: = 6; Parse (i+1); ) Else (print_string "error"; Parse (i+1); )) in parse 0
Plai 2:everything about Parser