我正在学习 OCaml,但我正在努力处理这个片段:
let found = ref false
let () =
while not (Queue.is_empty q) && not !found do
let next = Queue.pop q
let () = found := (next.subtotal == total)
done
while 主体中的第二个 let 无法编译,错误显示“建议加入”。事实上,当我在第一个 let 之后添加一个“in”,并从第二行中删除“let”时,它就会编译。
但我不明白为什么需要这个? Ocaml 通常不会将新的“let”解释为就好像最后一行后面有一个“in”吗? 例如。当我将这两个 let 移到 while 块之外时,它们编译得很好。
OCaml 区分了局部定义和模块级定义。在本地定义中,如
let g x =
let y = 2 in (...)
名称
y
仅定义为 2
子表达式内的 (...)
。
特别是,这意味着该名称只是一个临时名称,稍后使用它将会出现错误
let g x =
let y = 3 in
x + y
let error = y (* the name y is unknown in this scope *)
相反,模块级定义如
module N = struct
let x = 0
let y = 1
end
let ok = N.x (* [x] is a valid field of the module [N] *)
定义当前(子)模块的新字段,该字段将始终位于此处(即使稍后它们被隐藏)。