gleamy/non_empty_list

This module provides a type and functions for working with non-empty lists, which are lists that are guaranteed to have at least one element.

Types

The NonEmptyList(a) type represents a non-empty list of elements of type a. It has two cases: End(first: a) for a list with a single element, and Next(first: a, rest: NonEmptyList(a)) for a list with multiple elements.

pub type NonEmptyList(a) {
  End(first: a)
  Next(first: a, rest: NonEmptyList(a))
}

Constructors

  • End(first: a)
  • Next(first: a, rest: NonEmptyList(a))

Functions

pub fn count(list: NonEmptyList(a)) -> Int

Returns the count (number of elements) in the non-empty list. Time complexity: O(n)

pub fn filter(
  list: NonEmptyList(a),
  predicate: fn(a) -> Bool,
) -> List(a)

Filters the elements of the non-empty list based on a predicate function and returns a (potentially empty) list with the elements that satisfy the predicate.

pub fn fold(
  over list: NonEmptyList(a),
  from initial: b,
  with fun: fn(b, a) -> b,
) -> b

Applies a function to every element in the non-empty list, accumulating the results with the provided initial accumulator value.

pub fn from_list(list: List(a)) -> Result(NonEmptyList(a), Nil)

Tries to create a non-empty list from a regular (potentially empty) list. Returns an error if the input list is empty.

pub fn map(
  list: NonEmptyList(a),
  transform: fn(a) -> b,
) -> NonEmptyList(b)

Applies a transformation function to every element in the non-empty list and returns a new non-empty list with the transformed elements.

pub fn reverse(list: NonEmptyList(a)) -> NonEmptyList(a)

Reverses the order of elements in the non-empty list.

pub fn to_list(list: NonEmptyList(a)) -> List(a)

Converts the non-empty list to a regular (potentially empty) list.

Search Document