Skip to content

Instantly share code, notes, and snippets.

@joshcough
Last active January 8, 2016 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshcough/4322c31ce35b4376f39d to your computer and use it in GitHub Desktop.
Save joshcough/4322c31ce35b4376f39d to your computer and use it in GitHub Desktop.
import scala.language.higherKinds
import scalaz.{Applicative, Traverse}
import scalaz.\/
import scalaz.std.list._
import scalaz.std.option._
import scalaz.syntax.either._
import scalaz.syntax.traverse._
object Mappy {
implicit def mapTrav[K] = new Traverse[Map[K, ?]] {
def traverseImpl[G[_], A, B](fa: Map[K, A])(f: A => G[B])
(implicit ap: Applicative[G]): G[Map[K, B]] =
ap.map(fa.toList.map { case (s,a) =>
ap.apply2(ap.point(s), f(a))((s,g) => (s,g))
}.sequenceU)(_.toMap)
}
def happy[F[_],A,B](m:Map[A, F[B]])
(implicit ap: Applicative[F]): F[Map[A,B]] = m.sequence
def main(args: Array[String]): Unit = {
println(happy(Map("hi" -> List(1,2), "bye" -> List(3,4))))
println(happy(Map("hi" -> Some(1), "bye" -> None)))
println(happy(Map("hi" -> Option(1), "bye" -> Option(2))))
type T[A] = String \/ A
println(happy[T,String,Int](
Map("hi" -> 1.right, "bye" -> 2.right))
)
println(happy[T,String,Int](
Map("hi" -> 1.right, "err" -> "err".left, "bye" -> 2.right))
)
}
}
/*
Output from main:
List(Map(hi -> 1, bye -> 3), Map(hi -> 1, bye -> 4), Map(hi -> 2, bye -> 3), Map(hi -> 2, bye -> 4))
None
Some(Map(hi -> 1, bye -> 2))
\/-(Map(hi -> 1, bye -> 2))
-\/(err)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment