Sorting OCaml中的排序函数不起作用
刚接触OCaml,我正在学习。我写了下面的函数。你觉得这个功能可以吗?我得到一个错误,但是这个算法有意义吗?我怎样才能纠正它呢Sorting OCaml中的排序函数不起作用,sorting,functional-programming,ocaml,Sorting,Functional Programming,Ocaml,刚接触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
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];;
让rec对l进行排序=
匹配
[] -> []
|h::t->插入h(排序t)
;;
让rec插入x l=
匹配
[]->[x]
|h::t->
如果您在此处给出的代码中有x,则使用时未定义的是insert
如果我把insert
的定义放在第一位,它对我来说很好。据我所知,这似乎是一个很好的代码(虽然不是一个特别快的排序)
我会尝试重新启动您的OCaml。你可能有一些旧的定义让人困惑。这是我自己弄明白的。我应该对函数进行排序,以便insert
位于sort
之前:)
(*对列表排序*)
让rec插入x l=
匹配
[]->[x]
|h::t->
如果x[]
|h::t->插入h(排序t)
;;
排序[3;2;8;4;1];;
sort
函数依赖于insert
函数和OCaml,调用sort
函数毫无意义,因为它还不知道insert
函数。因此,改变函数定义的顺序可以解决这个问题
(* 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];;