0
fun main() {
    val list = listOf(1, 2, 3, 4, 5) 

    if (list.isNotEmpty()) {
        Nel(list[0], list.subList(1, list.lastIndex))
    }
}

According to arrow documents, it seems be able to do it through Semigroup or Monad binding. However, there is no code to replace List with NonEmptyList.

Is there a better way to replace List withNonEmptyList without using subList?

galcyurio
  • 1,776
  • 15
  • 25

2 Answers2

6

There is a companion function fromList that return an Option<NonEmptyList> or if you are sure use fromListUnsafe:

val list = listOf(1, 2, 3, 4, 5)

val nelistOption = NonEmptyList.fromList(list)

val nelist = NonEmptyList.fromListUnsafe(list)
Rene
  • 5,730
  • 17
  • 20
3

Arrow 1.1.3 has introduced a more Koltin idiomatic way to achieve this with the introduction of Iterable.toNonEmptyListOrNull(): NonEmptyList?

Example:

val list: List<Int> = listOf(1, 2, 3)
val nonEmptyList: NonEmptyList<Int>? = list.toNonEmptyListOrNull()

To get the old Option type one can use the toOption() extension function

val list: List<Int> = listOf(1, 2, 3)
val nonEmptyList: Option<NonEmptyList<Int>> = list.toNonEmptyListOrNull().toOption()

or use Option.fromNullable()

val list: List<Int> = listOf(1, 2, 3)
val nonEmptyList: Option<NonEmptyList<Int>> = Option.fromNullable(list.toNonEmptyListOrNull())

The NonEmptyList.fromList() function is now deprecated in favor of toNonEmptyListOrNull.

Stylianos Gakis
  • 862
  • 8
  • 19