如何在scala列表中找到可重复元素的数量 [英] How to find count of repeatable elements in scala list

查看:340
本文介绍了如何在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

任何指针将不胜感激

推荐答案

There is also a method for this in GenSeqLike (which List inherit from): prefixLength. That makes a very short answer:

s.prefixLength(_==s.head)

这篇关于如何在scala列表中找到可重复元素的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆