Skip to content

Instantly share code, notes, and snippets.

@fomkin
Last active July 29, 2016 07:32
Show Gist options
  • Save fomkin/a39b16983487c2ed92a1b054d3c83cc9 to your computer and use it in GitHub Desktop.
Save fomkin/a39b16983487c2ed92a1b054d3c83cc9 to your computer and use it in GitHub Desktop.
implicit def IterableW[F[_], T](implicit w: W[T], ev: F[T] <:< Iterable[T]) = {
new W[F[T]] {
def write(xs: F[T]) = {
ev(xs).map(x => w.write(x)).mkString(", ")
}
}
}
def writeIterable[F[_], T](xs: F[T])(implicit w: W[T], ev: F[T] <:< Iterable[T]) = {
ev(xs).map(x => w.write(x)).mkString(", ")
}
implicitly[W[Seq[(Int,Int)]]].write(Seq((1 -> 2), (2 -> 3), (3 -> 4)))
// "1:2, 2:3, 3:4"
implicitly[W[Map[Int, Int]]]
// error: could not find implicit value for parameter e: W[Map[Int,Int]]
// But
writeIterable(Map(1 -> 2, 2 -> 3, 3 -> 4))
// "1:2, 2:3, 3:4"
// ------------------------
trait W[T] {
def write(x: T): String
}
implicit object IntW extends W[Int] {
def write(x: Int) = x.toString
}
implicit def TupleW[A, B](implicit wa: W[A], wb: W[B]) = new W[(A, B)] {
def write(tpl: (A, B)) = wa.write(tpl._1) + ":" + wb.write(tpl._2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment