1

How can I find two successive and same values in a Stream and return this "duplicate-value":

def succ: Stream[Int] => Int = str => ...

For instance Stream(1, 2, 4, 3, 5, 5, 2, 2) would result in 5.

How would one do that?

Xavier Guihot
  • 54,987
  • 21
  • 291
  • 190
appcodix
  • 342
  • 2
  • 15

3 Answers3

2

You could use a mix of Stream.sliding and Stream.collectFirst:

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

which produces:

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)

or None if no successive elements share the same value.


As per your comment, in order to return 0 instead of None when no successive elements share the same value, you can apply .getOrElse(0) at the end of the pipeline:

def succ(stream: Stream[Int]): Int =
  stream.sliding(2).collectFirst { case Stream(x, y) if x == y => x }.getOrElse(0)
Xavier Guihot
  • 54,987
  • 21
  • 291
  • 190
  • If there are no successive values it returns 0. f there is such a value it should return it directly. – appcodix Jul 07 '18 at 21:08
2

Zipping the stream with its tail is another way of doing this which seems to handle single element Streams. Empty streams are handled explicitly:

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)
}
Xavier Guihot
  • 54,987
  • 21
  • 291
  • 190
Jack Leow
  • 21,945
  • 4
  • 50
  • 55
0

How about using simple recursion?

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)
}

This doesn't work if there are no subsequent duplicates found, for that you'll have to change your return type to Option[Int] and add some additional checks.

Dennis Hunziker
  • 1,293
  • 10
  • 19