具有相同相邻值的Scala列表

时间:2019-05-29 11:05:33

标签: scala functional-programming

我有这个列表:

List("Black","Black","Green","White")

如何检查列表中是否有两个相同的相邻值?像这样:

List("Black","Black","Green","White") true

List("Black","Yellow","Green","White") false

List("Black","Yellow","Black","Yellow") false

3 个答案:

答案 0 :(得分:15)

除了Valy Dia的解决方案之外,您还可以编写:

list.sliding(2).exists(_.distinct.size == 1)

REPL会话

scala> def check[A](l: Seq[A]): Boolean = l.sliding(2).exists(_.distinct.size == 1)
check: [A](l: Seq[A])Boolean

scala> check("A" :: "B" :: Nil)
res0: Boolean = false

scala> check("A" :: "B" :: "B" ::Nil)
res1: Boolean = true

scala> check("A" :: "B" :: "C":: "B" ::Nil)
res2: Boolean = false

答案 1 :(得分:7)

您可以尝试:

def check[A](l: List[A]): Boolean = 
 l.zip(l.tail).exists{ case (x,y) => x == y }

check(List("Black","Black","Green","White"))
//res5: Boolean = true

check(List("Black","Yellow","Green","White"))
//res6: Boolean = false

check(List("Black","Yellow","Black","Yellow"))
//res7: Boolean = false

答案 2 :(得分:4)

val listA = List("Black","Black","Green","White")

listA.sliding(2).map{case a::b::_ if a == b => true else false}.contains(true)