cats
58d680f238b1
add init and size methods to NonEmptyList (#1628)
João Ferreira
1 day ago
* add init and size methods to NonEmptyList * add tests * change NonEmptyList.last implementation * Revert "change NonEmptyList.last implementation" This reverts commit 5745f5b3c9ad0ebd1ca8accae2d740fdf515e7de.

15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
*/ 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 */ def map[B](f: A => B): NonEmptyList[B] = NonEmptyList(f(head), tail.map(f))

236 237 238 239 240 241 242 243 244 245 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
forAll { nel: NonEmptyList[Int] => nel.last should === (nel.toList.last) } }
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) } }
About FluentSend Feedback