3

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

2 回答 2

3

首先,let x = y;OCaml 中没有表达式,正确的语法是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 ;;
于 2014-11-22T14:40:15.870 回答
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) - 因为数组是一个关键字,但我认为没有必要。

于 2014-11-22T14:04:24.893 回答