# NonEmptyList

> A list that is never empty, so head, last and reduce are total.

Source: https://docs.pyrula.io/primitives/non-empty-list/

`NonEmptyList[T]` is an immutable list with at least one element, enforced at construction. `head`, `last` and `reduce` return `T` directly rather than an `Option`.

```python
from pyrula import NonEmptyList, IList

nel = NonEmptyList(1, 2, 3, 4)   # the first argument is the head; zero arguments raise TypeError
nel.head()                       # 1
nel.last()                       # 4
nel.reduce(lambda a, b: a + b)   # 10, seeded by head
nel.tail()                       # IList([2, 3, 4]), possibly empty
```

When the input may be empty, `from_list` returns an `Option`:

```python
NonEmptyList.from_list([1, 2, 3])      # Some(NonEmptyList(1, 2, 3))
NonEmptyList.from_list([])             # Nothing
NonEmptyList.from_list(IList([10, 20]))  # Some(NonEmptyList(10, 20))
```

`map`, `flat_map`, `append` and `prepend` stay non-empty. `flat_map` needs a function that returns a `NonEmptyList`.

```python
NonEmptyList(1, 2, 3).map(lambda x: x * 10)                   # NonEmptyList(10, 20, 30)
NonEmptyList(1, 2).append(3)                                  # NonEmptyList(1, 2, 3)
NonEmptyList(1, 2).flat_map(lambda x: NonEmptyList(x, x * 10))  # NonEmptyList(1, 10, 2, 20)
```

Convert with `to_list()`, `to_ilist()` or `list(nel)`. `fold_left(init, f)` takes an explicit seed.
