gpt4 book ai didi

arrays - 对数组进行排序 命令式 ocaml

转载 作者:行者123 更新时间:2023-12-02 09:12:45 28 4
gpt4 key购买 nike

我正在做一个相当简单的示例来学习如何使用 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 ;;

关于arrays - 对数组进行排序 命令式 ocaml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27077555/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com