From 58d680f238b13beb24195a2a9f404769212b5dcc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Ferreira?= Date: Wed, 26 Apr 2017 23:07:02 +0100 Subject: [PATCH] add init and size methods to NonEmptyList (#1628) * add init and size methods to NonEmptyList * add tests * change NonEmptyList.last implementation * Revert "change NonEmptyList.last implementation" This reverts commit 5745f5b3c9ad0ebd1ca8accae2d740fdf515e7de. --- .../main/scala/cats/data/NonEmptyList.scala | 42 +++++++++++++++++++ .../scala/cats/tests/NonEmptyListTests.scala | 12 ++++++ 2 files changed, 54 insertions(+) diff --git a/core/src/main/scala/cats/data/NonEmptyList.scala b/core/src/main/scala/cats/data/NonEmptyList.scala index 4c03eb5a42..a3c3b13817 100644 --- a/core/src/main/scala/cats/data/NonEmptyList.scala +++ b/core/src/main/scala/cats/data/NonEmptyList.scala @@ -17,14 +17,56 @@ final case class NonEmptyList[+A](head: A, tail: List[A]) { /** * Return the head and tail into a single list + * {{{ + * scala> import cats.data.NonEmptyList + * scala> val nel = NonEmptyList.of(1, 2, 3, 4, 5) + * scala> nel.toList + * res0: scala.collection.immutable.List[Int] = List(1, 2, 3, 4, 5) + * }}} */ def toList: List[A] = head :: tail + /** + * Selects the last element + * {{{ + * scala> import cats.data.NonEmptyList + * scala> val nel = NonEmptyList.of(1, 2, 3, 4, 5) + * scala> nel.last + * res0: Int = 5 + * }}} + */ def last: A = tail.lastOption match { case None => head case Some(a) => a } + /** + * Selects all elements except the last + * + * {{{ + * scala> import cats.data.NonEmptyList + * scala> val nel = NonEmptyList.of(1, 2, 3, 4, 5) + * scala> nel.init + * res0: scala.collection.immutable.List[Int] = List(1, 2, 3, 4) + * }}} + */ + def init: List[A] = tail match { + case Nil => List.empty + case t => head :: t.init + } + + /** + * The size of this NonEmptyList + * + * {{{ + * scala> import cats.data.NonEmptyList + * scala> val nel = NonEmptyList.of(1, 2, 3, 4, 5) + * scala> nel.size + * res0: Int = 5 + * }}} + */ + def size: Int = 1 + tail.size + /** * Applies f to all the elements of the structure */ diff --git a/tests/src/test/scala/cats/tests/NonEmptyListTests.scala b/tests/src/test/scala/cats/tests/NonEmptyListTests.scala index a1d501314e..7773f9d354 100644 --- a/tests/src/test/scala/cats/tests/NonEmptyListTests.scala +++ b/tests/src/test/scala/cats/tests/NonEmptyListTests.scala @@ -238,6 +238,18 @@ class NonEmptyListTests extends CatsSuite { } } + test("NonEmptyList#init is consistent with List#init") { + forAll { nel: NonEmptyList[Int] => + nel.init should === (nel.toList.init) + } + } + + test("NonEmptyList#size is consistent with List#size") { + forAll { nel: NonEmptyList[Int] => + nel.size should === (nel.toList.size) + } + } + test("NonEmptyList#sorted is consistent with List#sorted") { forAll { nel: NonEmptyList[Int] => nel.sorted.toList should === (nel.toList.sorted)