Skip to content

Commit

Permalink
add Foldable#distinctBy (#1354)
Browse files Browse the repository at this point in the history
  • Loading branch information
xuwei-k committed May 21, 2017
1 parent 8f38b26 commit bfeb8c8
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 0 deletions.
3 changes: 3 additions & 0 deletions core/src/main/scala/scalaz/Foldable.scala
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,9 @@ trait Foldable[F[_]] { self =>
else seen
}.reverse

def distinctBy[A, B: Equal](fa: F[A])(f: A => B): IList[A] =
distinctE(fa)(Equal.equalBy(f))

def collapse[X[_], A](x: F[A])(implicit A: ApplicativePlus[X]): X[A] =
foldRight(x, A.empty[A])((a, b) => A.plus(A.point(a), b))

Expand Down
1 change: 1 addition & 0 deletions core/src/main/scala/scalaz/syntax/FoldableSyntax.scala
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ final class FoldableOps[F[_],A] private[syntax](val self: F[A])(implicit val F:
final def minimumBy[B: Order](f: A => B): Option[A] = F.minimumBy(self)(f)
final def distinct(implicit A: Order[A]): IList[A] = F.distinct(self)
final def distinctE(implicit A: Equal[A]): IList[A] = F.distinctE(self)
final def distinctBy[B: Equal](f: A => B): IList[A] = F.distinctBy(self)(f)
final def longDigits(implicit d: A <:< Digit): Long = F.longDigits(self)
final def empty: Boolean = F.empty(self)
final def element(a: A)(implicit A: Equal[A]): Boolean = F.element(self, a)
Expand Down
7 changes: 7 additions & 0 deletions tests/src/test/scala/scalaz/FoldableTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,13 @@ object FoldableTest extends SpecLite {
if (xs.length > 0) xs.distinctE(Equal.equal((_,_) => true)).length must_== 1
}

"distinctBy" ! {
case class Foo(a: Int, b: String)
val xs = IList(Foo(1, "x"), Foo(2, "x"), Foo(1, "y"))
xs.distinctBy(_.a) must_== IList(Foo(1, "x"), Foo(2, "x"))
xs.distinctBy(_.b) must_== IList(Foo(1, "x"), Foo(1, "y"))
}

"sumr1Opt" ! forAll {
(xs: List[String]) => xs match {
case Nil => xs.sumr1Opt must_== None
Expand Down

0 comments on commit bfeb8c8

Please sign in to comment.