排序列表下面是排序任何列表代碼: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