本文介绍了OCaml 编译器在“in"上报告语法错误但交互式解释器运行没有缺陷的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码在 https://try.ocamlpro.com/

The following code runs without error on https://try.ocamlpro.com/

open Printf

let l = ref [] in
for i = 3 downto 0 do
  l := i :: !l
done;
List.iter (printf "%d " ) !l

但是在 Linux 上使用 ocamloptocamlc 编译器时会触发语法错误.

but it triggers a syntax error when using ocamlopt or ocamlc compiler on Linux.

ocamlc array.ml -o array
let l = ref [] in
               ^^
Error: Syntax error

推荐答案

语法错误可能隐藏在您没有包含的代码中.看来你已经写了

The syntax error is probably hidden in the code that you did not include.It seems probable that you have written

open Printf
let l = ref [] in
for i = 3 downto 0 do
  l := i :: !l
done;
List.iter (printf "%d " ) !l

这是一个语法错误,因为顶级表达式不能跟在非表达式顶级项之后.这就是语法错误出现在 in 上的原因:此位置只允许顶级定义(因此没有 in).

which is a syntax error because a toplevel expression cannot follow a non-expression toplevel item. This is why the syntax error is on the in: only toplevel definitions (thus with no in) are allowed at this location.

这就是为什么通常建议使用顶级单元定义而不是表达式的原因:

This is why it is generally advised to use toplevel unit definition rather than expression:

open Printf
let () =
  let l = ref [] in
  for i = 3 downto 0 do
    l := i :: !l
  done;
  List.iter (printf "%d " ) !l

通过这个小小的改变,你只有顶级定义,你不需要记住顶级表达式的规则.

With this little change, you only have toplevel definitions and you don't need to memorize the rule for toplevel expressions.

另一个简单的选择是考虑所有顶级表达式都应该由 ;; 引入:

Another simple option is to consider that all toplevel expression should be introduced by ;;:

open Printf

;; let l = ref [] in
  for i = 3 downto 0 do
    l := i :: !l
  done;
  List.iter (printf "%d " ) !l

这篇关于OCaml 编译器在“in"上报告语法错误但交互式解释器运行没有缺陷的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 05:14