Skip to content

List(T)

struct Monads::List(T) < Monad(T)

Includes Comparable(List), Indexable(T), and Iterator(T). Wraps an Array(T) and exposes it as a monad. See the List guide.

Construction

List[*args] (macro)

Builds a list from the given elements.

crystal
Monads::List[1, 2, 3] == Monads::List.new([1, 2, 3]) # => true

.new(value : Array(T))

Wraps an existing array.

.return(value)

Wraps a single value into a one-element list: List[value].

Monad operations

MethodDescription
fmap(lambda : T -> U)Map over every element, returning a List(U).
bind(lambda : T -> List(U))Map each element to a List and concatenate.

Collection helpers

MethodDescription
head : Maybe(T)First element as a Maybe (Nothing if empty).
tail : List(T)The list without its first element.
lastThe last element.
+(other : List)Concatenate two lists.
reverseReversed list.
sort / sort(&block) / sort_by(&block)Sorted list.
permutationsAll permutations, as a List of Lists.
subsequencesAll non-empty subsequences plus the empty list.
join(sep = "")Join elements into a String.
size / empty?Size and emptiness.
nextIterator protocol — yields the next element or stops.
<=>(other : List)Compares the underlying arrays.

Because List includes Indexable, methods like [], each, map, and to_a from the standard library are also available.

crystal
Monads::List[1, 2, 3].head        # => Just(1)
Monads::List[1, 2, 3].tail        # => List[2, 3]
Monads::List[1, 2] + Monads::List[3] # => List[1, 2, 3]

Released under the MIT License.