如何在scala列表中找到可重复元素的数量
问题描述:
假设您有一个List(1,1,1,4,4,1)
,并且必须计算连续重复出现在列表开头的元素多少次.在上面的示例中,方法应返回3.在此方法中,我们只关心第一个元素.
Suppose you have a List(1,1,1,4,4,1)
and have to calculate how many times is element that is a head of the list consecutively repeated. In the example above, method should return 3. In this method we only care about the first element.
我走到了这么远,被卡住了.给定第一个不可重复的角色,我想休息一下,怎么办?
I got this far and got stuck. Given a the first non repeatable character, i'd like to break, how how?
def firstRepeated [X] (xs: List[X]) : Int = xs match {
case Nil => 0
case y::ys => ys match {
case Nil => 0
case z::zs => if (y == z) 1 + firstRepeated(zs) else // break
}
}
此外,在上面的代码中,我认为我没有正确处理列表为z::Nil
Also, in the code above, i don't think i am properly handling a case when list is z::Nil
任何指针将不胜感激