Scala 如何在一个流中找到两个连续且相同的值?

Scala 如何在一个流中找到两个连续且相同的值?,scala,stream,duplicates,return,scala-streams,Scala,Stream,Duplicates,Return,Scala Streams,如何在流中找到两个连续且相同的值并返回此“重复值”: 例如流(1,2,4,3,5,5,2,2)将导致5 如何做到这一点?您可以混合使用和: 产生: Stream(1, 2, 4, 3, 5, 5, 2, 2) .sliding(2) // Stream(Stream(1, 2), Stream(2, 4), Stream(4, 3), ... .collectFirst { case Stream(x, y) if x == y => x } // Some(5) 或None如果

如何在
流中找到两个连续且相同的值并返回此“重复值”:

例如
流(1,2,4,3,5,5,2,2)
将导致
5

如何做到这一点?

您可以混合使用和:

产生:

Stream(1, 2, 4, 3, 5, 5, 2, 2)
  .sliding(2) // Stream(Stream(1, 2), Stream(2, 4), Stream(4, 3), ...
  .collectFirst { case Stream(x, y) if x == y => x } // Some(5)
None
如果没有连续的元素共享相同的值


根据您的评论,为了在没有连续元素共享相同的值时返回
0
而不是
None
,您可以在管道末尾应用
。getOrElse(0)

def succ(stream: Stream[Int]): Int =
  stream.sliding(2).collectFirst { case Stream(x, y) if x == y => x }.getOrElse(0)
您可以混合使用和:

产生:

Stream(1, 2, 4, 3, 5, 5, 2, 2)
  .sliding(2) // Stream(Stream(1, 2), Stream(2, 4), Stream(4, 3), ...
  .collectFirst { case Stream(x, y) if x == y => x } // Some(5)
None
如果没有连续的元素共享相同的值


根据您的评论,为了在没有连续元素共享相同的值时返回
0
而不是
None
,您可以在管道末尾应用
。getOrElse(0)

def succ(stream: Stream[Int]): Int =
  stream.sliding(2).collectFirst { case Stream(x, y) if x == y => x }.getOrElse(0)

使用简单递归怎么样

def succ: Stream[Int] => Int = {
  def rec(x: Int, xs: Stream[Int]): Int = {
    if (x == xs.head) x
    else rec(xs.head, xs.tail)
  }

  (str: Stream[Int]) => rec(str.head, str.tail)
}

如果没有找到后续的重复项,这将不起作用,因此您必须将返回类型更改为
Option[Int]
,并添加一些附加检查。

使用简单递归如何

def succ: Stream[Int] => Int = {
  def rec(x: Int, xs: Stream[Int]): Int = {
    if (x == xs.head) x
    else rec(xs.head, xs.tail)
  }

  (str: Stream[Int]) => rec(str.head, str.tail)
}

如果没有找到后续的重复项,这将不起作用,因为您必须将返回类型更改为
选项[Int]
,并添加一些附加检查。

用尾部压缩流是另一种处理单元素流的方法。空流被显式处理:

def succ: Stream[Int] => Int = {
  case Stream() => 0
  case str =>
    str.zip(str.tail).
    find { case (l, r) => l == r }.
    map { case (x, _) => x }.
    getOrElse(0)
}

用尾部压缩流是另一种处理单元素流的方法。空流被显式处理:

def succ: Stream[Int] => Int = {
  case Stream() => 0
  case str =>
    str.zip(str.tail).
    find { case (l, r) => l == r }.
    map { case (x, _) => x }.
    getOrElse(0)
}

如果没有连续值,则返回0。如果有这样一个值,它应该直接返回。如果没有连续的值,它将返回0。如果有这样一个值,它应该直接返回它。