命令式代码中的语法错误

问题描述 投票:0回答:2
exception Error of (string);;
let v = ref true;;
let e = Error("Fail");;
let h = ref false;;
while !h <> true do
  let x = read_int();
  let y = read_int();
  try
    let res = x / y in
    Printf.printf "result = %d" res;
    h := true;
  with
    Division_by_zero -> raise e
done;;

返回“done ;;”行中的语法错误,但我不知道为什么。

compiler-errors syntax-error ocaml
2个回答
4
投票
let x = read_int();

是一个顶级的定义,而不是一个表达。表达形式将是

let x = read_int() in ...

更一般地说,你似乎非常大量地模仿一种强制性的类似Algol的风格,这种风格大多会让你感到困惑并导致很多痛苦。您应该尝试编写没有可变性的代码,分号(在OCaml中是“序列运算符”,而不是行/语句终止符)和命令式迭代。

您可能还会发现类似JavaScript的ReasonML syntax更熟悉且更容易处理,但它当然是另一件事,设置和OCaml学习资源必须翻译,所以可能不值得额外的麻烦。


1
投票

我强烈建议患有OCaml语法错误的人使用适当的缩进工具,例如ocp-indent并尝试缩进代码行。从自动缩进结果中,当代码与您的意图不同时,您通常可以找到正确的问题所在:

exception Error of (string);;
let v = ref true;;
let e = Error("Fail");;
let h = ref false;;
while !h <> true do
  let x = read_int();
    let y = read_int();  (* <= this is still in the definition of x *)
      try
        let res = x / y in
        Printf.printf "result = %d" res;
        h := true;
      with
        Division_by_zero -> raise e
done;;
© www.soinside.com 2019 - 2024. All rights reserved.