Skip to content

Commit

Permalink
Add Foldable.intercalate
Browse files Browse the repository at this point in the history
  • Loading branch information
peterneyens committed Jan 6, 2017
1 parent 468e753 commit 5fb96ec
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
16 changes: 16 additions & 0 deletions core/src/main/scala/cats/Foldable.scala
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,22 @@ import simulacrum.typeclass
def nonEmpty[A](fa: F[A]): Boolean =
!isEmpty(fa)

/**
* Intercalate/insert an element between the existing elements while folding.
*
* {{{
* scala> import cats.implicits._
* scala> Foldable[List].intercalate(List("a","b","c"), "-")
* res0: String = a-b-c
* scala> Foldable[Vector].intercalate(Vector(1,2,3), 1)
* res1: Int = 8
* }}}
*/
def intercalate[A](fa: F[A], a: A)(implicit A: Monoid[A]): A =
reduceLeftOption(fa){ (acc, aa) =>
A.combine(acc, A.combine(a, aa))
}.getOrElse(A.empty)

def compose[G[_]: Foldable]: Foldable[λ[α => F[G[α]]]] =
new ComposedFoldable[F, G] {
val F = self
Expand Down
8 changes: 8 additions & 0 deletions tests/src/test/scala/cats/tests/FoldableTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,14 @@ abstract class FoldableCheck[F[_]: Foldable](name: String)(implicit ArbFInt: Arb
fa.reduceRightOption((x, ly) => ly.map(x - _)).value should === (list.reduceRightOption(_ - _))
}
}

test("intercalate") {
forAll { (fa: F[Int], a: Int) =>
val list = fa.toList
val sum = list.sum + (math.max(list.length - 1, 0) * a)
fa.intercalate(a) should === (sum)
}
}
}

class FoldableTestsAdditional extends CatsSuite {
Expand Down

0 comments on commit 5fb96ec

Please sign in to comment.