From fe64eaf41ab62ef38546e4f0202de2c04175ec43 Mon Sep 17 00:00:00 2001 From: Andrea Fiore Date: Sat, 11 Jun 2016 14:25:47 +0100 Subject: [PATCH] Add size to Foldable This addresses part of what is proposed in #1091. --- core/src/main/scala/cats/Foldable.scala | 3 +++ tests/src/test/scala/cats/tests/FoldableTests.scala | 6 ++++++ 2 files changed, 9 insertions(+) diff --git a/core/src/main/scala/cats/Foldable.scala b/core/src/main/scala/cats/Foldable.scala index 54303abdd39..d470a9eca26 100644 --- a/core/src/main/scala/cats/Foldable.scala +++ b/core/src/main/scala/cats/Foldable.scala @@ -1,6 +1,7 @@ package cats import scala.collection.mutable +import cats.std.long._ import simulacrum.typeclass /** @@ -56,6 +57,8 @@ import simulacrum.typeclass } } + def size[A](fa: F[A]): Long = foldMap(fa)(_ => 1) + /** * Fold implemented using the given Monoid[A] instance. */ diff --git a/tests/src/test/scala/cats/tests/FoldableTests.scala b/tests/src/test/scala/cats/tests/FoldableTests.scala index 512edaf9e3a..7788e43f6fe 100644 --- a/tests/src/test/scala/cats/tests/FoldableTests.scala +++ b/tests/src/test/scala/cats/tests/FoldableTests.scala @@ -10,6 +10,12 @@ abstract class FoldableCheck[F[_]: Foldable](name: String)(implicit ArbFInt: Arb def iterator[T](fa: F[T]): Iterator[T] + test("size") { + forAll { (fa: F[Int]) => + fa.size should === (iterator(fa).size.toLong) + } + } + test("summation") { forAll { (fa: F[Int]) => val total = iterator(fa).sum