Skip to content

Commit

Permalink
Add TraverseFilter instance for Map to alleycats
Browse files Browse the repository at this point in the history
  • Loading branch information
dcastro committed Feb 13, 2019
1 parent 5e5147b commit 21acd92
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
1 change: 1 addition & 0 deletions alleycats-core/src/main/scala/alleycats/std/all.scala
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,4 @@ import export._
with LegacyTryInstances
with LegacyIterableInstances
with MapInstances
with MapInstancesBinCompat0
20 changes: 19 additions & 1 deletion alleycats-core/src/main/scala/alleycats/std/map.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package std

import cats._

object map extends MapInstances
object map extends MapInstances with MapInstancesBinCompat0

trait MapInstances {

Expand Down Expand Up @@ -59,3 +59,21 @@ trait MapInstances {
collectFirst(fa)(Function.unlift(f))
}
}

trait MapInstancesBinCompat0 extends MapInstances {
implicit def mapTraverseFilter[K]: TraverseFilter[Map[K, ?]] =
new TraverseFilter[Map[K, ?]] {
def traverse: Traverse[Map[K, ?]] = alleycatsStdInstancesForMap

def traverseFilter[G[_], A, B](fa: Map[K, A])(f: A => G[Option[B]])(implicit G: Applicative[G]): G[Map[K, B]] = {
val gba: Eval[G[Map[K, B]]] = Always(G.pure(Map.empty))
Foldable
.iterateRight(fa, gba) { (kv, lbuf) =>
G.map2Eval(f(kv._2), lbuf)({ (ob, buf) =>
ob.fold(buf)(b => buf + (kv._1 -> b))
})
}
.value
}
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
package alleycats.tests

import cats.laws.discipline.SerializableTests
import cats.laws.discipline.arbitrary._
import cats.laws.discipline.{SerializableTests, TraverseFilterTests}
import cats.Traverse
import alleycats.std.all._

class MapSuite extends AlleycatsSuite {
checkAll("Traverse[Map[Int, ?]]", SerializableTests.serializable(Traverse[Map[Int, ?]]))

checkAll("TraverseFilter[Map[Int, ?]]", TraverseFilterTests[Map[Int, ?]].traverseFilter[Int, Int, Int])
}

0 comments on commit 21acd92

Please sign in to comment.