NonEmptyList
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.
from pyrula import NonEmptyList, IList
nel = NonEmptyList(1, 2, 3, 4) # the first argument is the head; zero arguments raise TypeErrornel.head() # 1nel.last() # 4nel.reduce(lambda a, b: a + b) # 10, seeded by headnel.tail() # IList([2, 3, 4]), possibly emptyWhen the input may be empty, from_list returns an Option:
NonEmptyList.from_list([1, 2, 3]) # Some(NonEmptyList(1, 2, 3))NonEmptyList.from_list([]) # NothingNonEmptyList.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.
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.