这是我的代码,我不明白为什么我不能做这笔钱。例如,我在输入中有这个列表[1; 1; 2; 2; 2; 2; 3; 3; 4; 3; 3; 3],我需要[2; 8; 6; 4; 9]。任何人都可以帮我解决我的问题吗?谢谢。
let rec compress l =
match l with
[] -> []
| [x] -> [x]
| x::y::xs when x<>y -> compress(xs)
| x::y::xs when x=y -> (x+y)::compress(y::xs)
答案 0 :(得分:2)
这是一个可能的解决方案,使用递归:
let compress l =
let rec loop last acc l =
match (l, last) with
| [], None -> []
| [], Some _ -> [acc]
| x::xs, None -> loop (Some x) acc (x::xs)
| x::xs, Some n when x = n -> loop last (n+acc) xs
| x::xs, _ -> acc :: loop (Some x) x xs
loop None 0 l
它使用一个加法参数acc
来累积结果,last
代表前一个元素。
答案 1 :(得分:2)
这是另一种可能的解决方案:
let compress l =
if List.isEmpty l then []
else
let rec loop (last, acc) xs =
let h = List.head acc
match xs with
| [] -> (last, acc)
| y::ys when y = last -> loop (y, (y + h)::List.tail acc) ys
| y::ys -> loop (y, y::acc) ys
let h = List.head l
List.tail l
|> loop (h, [h])
|> (snd >> List.rev)
compress l
val it : int list = [2; 8; 6; 4; 9]
请注意,循环函数是尾递归的。