Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sorting OCaml中的排序函数不起作用_Sorting_Functional Programming_Ocaml - Fatal编程技术网

Sorting 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

刚接触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];;
让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];;