Skip to content

Instantly share code, notes, and snippets.

@ummels
Created November 26, 2014 17:05

Revisions

  1. ummels created this gist Nov 26, 2014.
    22 changes: 22 additions & 0 deletions mergestream.scala
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    object Util {
    /** Merges a collection of streams into a single stream.
    *
    * Returns a sorted stream if all input streams are sorted.
    */
    def mergeStreams[A](streams: Traversable[Stream[A]])(implicit ord: Ordering[A]): Stream[A] = {
    val streams1 = streams.toList filterNot (_.isEmpty) sortBy (_.head)
    if (streams1.isEmpty)
    Stream.empty
    else {
    val first = streams1.head
    first.head #:: mergeStreams(first.tail :: streams1.tail)
    }
    }

    /** Merges several streams into a single stream.
    *
    * Returns a sorted stream if all input streams are sorted.
    */
    def mergeStreams[A](streams: Stream[A]*)(implicit ord: Ordering[A]): Stream[A] =
    mergeStreams(streams)
    }