ce/token.ml

38 lines
702 B
OCaml
Raw Normal View History

2022-01-10 01:31:47 +09:00
type t =
| Int of int
| Ident of string
| Plus
| Minus
| Asterisk
| Slash
| LParen
| RParen
let of_char = function
| '+' -> Plus
| '-' -> Minus
| '*' -> Asterisk
| '/' -> Slash
| '(' -> LParen
| ')' -> RParen
| _ -> invalid_arg "Token.of_char"
let of_string str =
let fc = Char.code str.[0] in
if Char.(code '0' <= fc && fc <= code '9') then
Int (int_of_string str)
else
match str with
| _ when String.length str = 1 -> of_char str.[0]
| _ -> failwith "Token.of_string"
let to_string = function
| Int n -> string_of_int n
| Ident s -> s
| Plus -> "+"
| Minus -> "-"
| Asterisk -> "*"
| Slash -> "/"
| LParen -> "("
| RParen -> ")"