(OCaml中)你如何消除連續重複的列表元素?
此解決方案
let compress l =
let rec compress_2 l e =
match l with
| [] -> [e]
| h::t -> if (h=e)
then (compress_2 t e)
else e::(compress_2 t)
in
match l with
| [] -> []
| h::t -> compress_2 t h;;
但是,爲什麼沒有這個解決方案的工作?
let rec compress (l: 'a list) : 'a list =
match l with
| [] -> []
| h::[] -> [h]
| h1::h2::t -> if h1=h2 then h2::(compress t) else h1::h2::(compress t) ;;
關於您的b)解決方案:考慮[1; 2; 2]的結果。它會工作,如果你在列表中留下h2像'else h1 :: compress(h2 :: t)' – lambdapower 2011-12-24 13:21:56