对数组进行排序命令式的ocaml

时间:2014-11-22 12:47:36

标签: arrays sorting ocaml imperative

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

2 个答案:

答案 0 :(得分:3)

首先,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 ;;

答案 1 :(得分:0)

代码中的以下修复可能有所帮助 - 至少要编译代码 - :

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;;

值得注意的是:声明局部变量,还有一些丢失的分号。 我将参数的名称(数组更改为toto)更改 - 因为数组是关键字,但我认为没有必要。