2

OCaml 的新手,我正在学习。我写了下面的函数。你说这个功能好吗?那么我得到一个错误,但算法有意义吗?我该如何纠正它。

let rec sort l =
    match l with 
    [] -> []
    |h::t -> insert h (sort t)
;;

let rec insert x l =
    match l with
    [] -> [x]
    |h::t ->
        if x <= h
            then x :: h :: t
    else h :: insert x t
;;


sort [3; 2; 8; 4; 1];;

我进入我的终端: Error: Unbound value sort

4

2 回答 2

1

在您在此处提供的代码中,它insert在您使用时未定义。

如果我把定义insert放在第一位,它对我来说很好。据我所知,这似乎是很好的代码(尽管不是特别快的排序)。

我会尝试再次从头开始启动您的 OCaml。您可能有一些令人困惑的旧定义。

于 2013-11-15T00:14:27.393 回答
0

我自己想通了。我应该把函数的顺序insert排在前面sort:)

(* Sort a list *)

let rec insert x l =
    match l with
    [] -> [x]
    |h::t ->
        if x <= h
            then x :: h :: t
    else h :: insert x t
;;

let rec sort l =
    match l with 
    [] -> []
    |h::t -> insert h (sort t)
;;




sort [3; 2; 8; 4; 1];;

sort函数依赖于该insert函数和 OCaml,调用该sort函数没有任何意义,因为它还不知道该insert函数。所以改变函数定义的顺序可以解决问题。

于 2013-11-15T00:14:54.890 回答