这是对任何给定列表进行排序的代码:
let rec sort lst =
match lst with
[] -> []
| head :: tail -> insert head (sort tail)
and insert elt lst =
match lst with
[] -> [elt]
| head :: tail -> if elt <= head then elt :: lst else head :: insert elt tail;;
Run Code Online (Sandbox Code Playgroud)
[来源:代码
但是,我收到未绑定错误:
Unbound value tail
# let rec sort lst =
match lst with
[] -> []
| head :: tail -> insert head (sort tail)
and insert elt lst =
match lst with
[] -> [elt]
| head :: tail -> if elt <= head then elt :: lst else head :: insert elt tail;;
Characters 28-29:
| head :: tail -> if elt <= head then elt :: lst else head :: insert elt tail;;
^
Error: Syntax error
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮我理解这里的问题吗?我没有在任何地方或代码中找到head或tail预定义
您的代码似乎是正确的,并且可以为我编译:
Objective Caml version 3.11.1
# let rec sort lst = ...
val sort : 'a list -> 'a list = <fun>
val insert : 'a -> 'a list -> 'a list = <fun>
# sort [ 1 ; 3 ; 9 ; 2 ; 5 ; 4; 4; 8 ; 4 ] ;;
- : int list = [1; 2; 3; 4; 4; 4; 5; 8; 9]
Run Code Online (Sandbox Code Playgroud)