尝试解析整数时出现错误

时间:2020-04-17 14:27:40

标签: ocaml interpreter

我正在尝试运行我在ocaml中创建的解释器,并且当我输入负值时,即让e1 =运行[PushI -2; PushI 2;少于] []。我的parse_int函数收到语法错误。我正在尝试编写该函数的允许输入负数的部分

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

1 个答案:

答案 0 :(得分:0)

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 = '-'"不是整数构造函数。您可以编写仅与整数11匹配的_,或者与任何整数匹配的n匹配任何整数,并将其绑定到名称n条款的其余部分。您可以查看manual了解更多信息。

如果您想检查字符串的第一个字符是否为-模式匹配不是正确的工具,只需使用if then else

不过,请注意,int_of_string在负整数上也能很好地工作,因此不需要您自己做那一部分。

无关,但我注意到您在parse_int函数中调用了parse_command。在这种情况下,您应该在parse_int之前定义parse_command