Ocaml 尝试分析整数时出错
我试图运行我用ocaml制作的解释器,当我输入一个负值时,即让e1=run[PushI-2;PushI-2;LessThan][]。我的parse_int函数出现语法错误。我试图写函数中允许输入负数的部分Ocaml 尝试分析整数时出错,ocaml,interpreter,Ocaml,Interpreter,我试图运行我用ocaml制作的解释器,当我输入一个负值时,即让e1=run[PushI-2;PushI-2;LessThan][]。我的parse_int函数出现语法错误。我试图写函数中允许输入负数的部分 type stackVal = I of int type command = PushI of int let rec run (commands : command list) (stack: stackVal list) : stackVal list = mat
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
| String.get n 0 = '-' -> Some -String.sub n 1 len
| n -> Some n
| exception _ -> None
parse_int
函数的模式匹配有问题
match int_of_string s with
| String.get n 0 = '-' -> Some -String.sub n 1 len
| n -> Some n
| exception _ -> None
此处的第一个子句无效,因为“String.get n 0='-'”
不是整数构造函数。您可以编写只匹配整数的1
或匹配任意整数的
或匹配任意整数的n
,并将其绑定到子句其余部分的名称n
。您可以查看以了解更多信息
如果要检查字符串的第一个字符是否为-
模式匹配不是正确的工具,只需使用If-then-else
但是,请注意,int\u of_string
在负整数上工作得很好,所以不需要自己完成这部分工作
不相关,但我注意到您在
parse_命令
函数中调用了parse_int
。在这种情况下,您应该在parse_命令
之前定义parse_int
我先前的回答可能误导了你。您的match子句无效,第一个子句不是必需的int\u of_string“-5”
应该已经起作用了