[我正在尝试运行我在ocaml中创建的解释器,并且当我输入负值时,即让e1 =运行[PushI -2; PushI 2;少于] []。我收到一个错误消息,因为它说我给了PushI函数两个参数,我假设他们正在谈论-符号和两个参数。因为执行(-2)是可行的。我可以进行哪些更改以使PushI -2成为可行的输入。
代码:
type stackVal =
I of int
type command = PushI of int
let rec run (commands : command list) (stack: stackVal list) : stackVal list =
match (commands , stack) with
| (PushI i :: rest, _ ) -> run rest (I i :: stack)
let to_string (s : stackVal) : string =
match s with
| I i -> string_of_int i
let parse_command (s:string) : command =
match take_while is_alpha (String.trim s) with
| ("PushI" , p) -> let Some i = parse_int (String.trim p) in PushI i
let parse_int (s : string) : int option =
match int_of_string s with
| n -> Some n
| exception _ -> None
[为了解决这个问题,parse_int
必须尝试查看第一个字符是否为-
(减号)字符(为了完整起见,也可能是+
)。解析了可选符号后,它可以为其余字符解析一个整数,并将该符号应用于解析后的值。
您可以使用String.get str 0
查看第一个字符,并使用String.sub
计算字符串的子字符串(其余数字)。您也可以使用正则表达式来处理更复杂的情况。
您可以执行PushI ~-1
。 ~-
无疑是int
否定运算符:https://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#VAL(~-)
换句话说,它没有-
之类的解析歧义。