我正在做一个相当简单的示例来学习如何使用 ocaml 作为命令式语言。 我的猜测是我搞乱了分号,但我在代码中找不到任何错误
let sort array =
for index = 0 to (Array.length array -1) do
let boole = ref false;
let pos = ref index;
let max = ref array.(index);
let p = ref !pos;
let m = ref !max;
while !pos <> (Array.lenght array -1 ) do
if array.(!pos) > !max then begin
max := array(!pos);
boole := true;
p := !pos
end
pos := !pos + 1
done;
if (!boole = true) then begin
array.(index) <- max;
array.(pos) <- m
end
done ;;
谢谢你。
编辑1:
如果有人遇到这个问题,我将发布正确的代码,因为即使使用正确的语法,上述代码也无法正确对数组进行排序:
let sort array =
for index = 0 to (Array.length array -1) do
let boole = ref false in
let pos = ref index in
let max = ref array.(index) in
let p = ref !pos in
let m = ref !max in
for i = !pos to (Array.length array -1) do
if (array.(i) > !max) then begin
pos :=i;
max := array.(!pos);
boole := true;
end;
done;
if (!boole = true) then begin
array.(!pos) <- !m;
array.(!p) <- !max;
end;
done ;;
首先,OCaml 中没有
let x = y;
表达式,正确的语法是 let x = y in
,而且你不应该忘记取消引用你的引用。
let sort array =
for index = 0 to (Array.length array -1) do
let boole = ref false in
let pos = ref index in
let max = ref array.(index) in
let p = ref !pos in
let m = ref !max in
while !pos <> (Array.length array -1 ) do
if array.(!pos) > !max then begin
max := array.(!pos);
boole := true;
p := !pos
end;
pos := !pos + 1;
done;
if (!boole = true) then begin
array.(index) <- !max;
array.(!pos) <- !m;
end;
done ;;
代码中的以下修复可能会有所帮助 - 至少可以编译代码 - :
let sort toto =
for index = 0 to (Array.length toto - 1) do
let boole = ref false in
let pos = ref index in
let max = ref toto.(index) in
let p = ref !pos in
let m = ref !max in
begin
while !pos <> (Array.length toto - 1 ) do
begin
if (toto.(!pos) > !max) then
begin
max := toto.(!pos);
boole := true;
p := !pos;
end;
pos := !pos + 1;
end
done;
if (!boole = true) then begin
toto.(index) <- !max;
toto.(!pos) <- !m
end
end
done;;
值得注意的是:局部变量的声明,以及一些缺少的分号。 我更改了参数的名称(array 为 toto) - 因为 array 是一个关键字,但我认为没有必要。