Skip to content

Commit

Permalink
Merge pull request #775 from mikejcurry/add-stream-show
Browse files Browse the repository at this point in the history
Adds Show[Stream]
  • Loading branch information
ceedubs committed Jan 5, 2016
2 parents 971f954 + 7e7ca84 commit 8b3c015
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
6 changes: 6 additions & 0 deletions core/src/main/scala/cats/std/stream.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package cats
package std

import scala.collection.immutable.Stream.Empty
import cats.syntax.show._

trait StreamInstances {
implicit val streamInstance: Traverse[Stream] with MonadCombine[Stream] with CoflatMap[Stream] =
Expand Down Expand Up @@ -58,6 +59,11 @@ trait StreamInstances {
override def isEmpty[A](fa: Stream[A]): Boolean = fa.isEmpty
}

implicit def streamShow[A: Show]: Show[Stream[A]] =
new Show[Stream[A]] {
def show(fa: Stream[A]): String = if(fa.isEmpty) "Stream()" else s"Stream(${fa.head.show}, ?)"
}

// TODO: eventually use algebra's instances (which will deal with
// implicit priority between Eq/PartialOrder/Order).

Expand Down
22 changes: 22 additions & 0 deletions tests/src/test/scala/cats/tests/StreamTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,26 @@ class StreamTests extends CatsSuite {

checkAll("Stream[Int] with Option", TraverseTests[Stream].traverse[Int, Int, Int, List[Int], Option, Option])
checkAll("Traverse[Stream]", SerializableTests.serializable(Traverse[Stream]))

test("show") {
Stream(1, 2, 3).show should === ("Stream(1, ?)")
Stream.empty[Int].show should === ("Stream()")
}

test("Show[Stream] is referentially transparent, unlike Stream.toString") {
forAll { stream: Stream[Int] =>
if (!stream.isEmpty) {
val unevaluatedStream = stream map identity
val initialShow = unevaluatedStream.show

// Evaluating the tail can cause Stream.toString to return different values,
// depending on the internal state of the Stream. Show[Stream] should return
// consistent values independent of internal state.
unevaluatedStream.tail
initialShow should === (unevaluatedStream.show)
} else {
stream.show should === (stream.toString)
}
}
}
}

0 comments on commit 8b3c015

Please sign in to comment.