Search code examples
scalastreamduplicatesreturnscala-streams

How to find two successive and same values in a Stream?


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?


Solution

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