Skip to content

Commit

Permalink
add init and size methods to NonEmptyList (#1628)
Browse files Browse the repository at this point in the history
* add init and size methods to NonEmptyList

* add tests

* change NonEmptyList.last implementation

* Revert "change NonEmptyList.last implementation"

This reverts commit 5745f5b.
  • Loading branch information
jtjeferreira authored and johnynek committed Apr 26, 2017
1 parent 6d4ad73 commit 58d680f
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
42 changes: 42 additions & 0 deletions core/src/main/scala/cats/data/NonEmptyList.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down
12 changes: 12 additions & 0 deletions tests/src/test/scala/cats/tests/NonEmptyListTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 58d680f

Please sign in to comment.