如何计算Ocaml中连续重复的数量
我正在尝试编写一个函数,它接受一个列表,并返回列表中连续重复元素的数量 例如,给定如何计算Ocaml中连续重复的数量,ocaml,Ocaml,我正在尝试编写一个函数,它接受一个列表,并返回列表中连续重复元素的数量 例如,给定[1;2;3;3;4;4;5],函数应返回2 这是我的初始实现,但不幸的是它总是返回0。我不太清楚虫子在哪里。 任何关于如何改进的帮助都将不胜感激 let rec count_successive_duplicates (lst: int list) (count: int) : (int) = match lst with | [] | [_]-> 0 | x :: y :: tl -&
[1;2;3;3;4;4;5]
,函数应返回2
这是我的初始实现,但不幸的是它总是返回0
。我不太清楚虫子在哪里。
任何关于如何改进的帮助都将不胜感激
let rec count_successive_duplicates (lst: int list) (count: int) : (int) =
match lst with
| [] | [_]-> 0
| x :: y :: tl ->
if x = y then count_successive_duplicates (y::tl) (count + 1) else count_successive_duplicates (y::tl) count
;;
let () =
print_int (count_successive_duplicates [1;2;3;3;4;4;5] 0)
似乎我做了一件傻事,总是返回基本情况的
0
,而不是计算的计数。以前的版本只是忽略了它接收到的计算的计数。现在可以这样做了:
let rec count_successive_duplicates lst count : (int) = match lst with
| [] | [_]-> count
| x :: y :: tl ->
if x = y then count_successive_duplicates (y::tl) (count + 1) else count_successive_duplicates (y::tl) count
;;
let () =
print_int (count_successive_duplicates [1;2;3;3;4;4;5] 0)
最后,您将希望返回带有计数的累加器,而不是0
始终:
let rec count_successive_duplicates (lst: int list) (count: int) : (int) =
match lst with
| [] | [_] -> count
(* ^^^^^ */)
| x :: y :: tl -> count_successive_duplicates (y::tl) (count + if x = y then 1 else 0)
你需要在某个地方获得最大值。您的计数当前确实有时会增加,但a)遇到新序列时不会重置b)最后它总是返回0
无论如何,我发现当递增的计数可用时,我没有使用它。谢谢你的提示。我现在看到了bug哦,我误解了你想做什么,我以为你想数一数最长的重复序列。但是是的,这只是一个小虫子。