排序列表下面是排序任何列表代码:OCaml中
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;;
[来源:Code
不过,我得到一个未绑定错误:
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
灿任何人请帮我理解这里的问题?我没有找到head
或tail
的任何地方,也没有在代码
但我不明白“head :: tail”模式的含义。你能解释一下吗? – 2010-05-03 07:06:12
类型列表是一种定义为具有两个构造函数的内置类型。一个是空列表'[]'。另一个是cons cell'::'。您所写的模式匹配与您可以为自己定义的类型编写的模式匹配没有区别,除了它们使用内置的0元构造函数[]和二进制::。 – 2010-05-03 07:52:11
在'head :: tail'模式中,变量head代表列表的第一个元素,tail代表列表的其余部分。 – 2010-05-03 07:53:11