Data.List.Compat

base-compat-0.13.1: A compatibility layer for base

Safe Haskell | Trustworthy
Language | Haskell2010

Data.List.Compat

Synopsis

- (!?) :: [a] -> Int -> Maybe a
- unsnoc :: [a] -> Maybe ([a], a)

# Documentation

(!?) :: [a] -> Int -> Maybe a infixl 9 #

List index (subscript) operator, starting from 0. Returns `Nothing` if the index is out of bounds

    >>> ['a', 'b', 'c'] !? 0
    Just 'a'
    >>> ['a', 'b', 'c'] !? 2
    Just 'c'
    >>> ['a', 'b', 'c'] !? 3
    Nothing
    >>> ['a', 'b', 'c'] !? (-1)
    Nothing

This is the total variant of the partial `!!` operator.

WARNING: This function takes linear time in the index.

unsnoc :: [a] -> Maybe ([a], a) #

\(\mathcal{O}(n)\). Decompose a list into `init` and `last`.

- If the list is empty, returns `Nothing`.
- If the list is non-empty, returns ``Just` (xs, x)`, where `xs` is the `init`ial part of the list and `x` is its `last` element.

Since: 4.19.0.0

    >>> unsnoc []
    Nothing
    >>> unsnoc [1]
    Just ([],1)
    >>> unsnoc [1, 2, 3]
    Just ([1,2],3)

Laziness:

    >>> fst <$> unsnoc [undefined]
    Just []
    >>> head . fst <$> unsnoc (1 : undefined)
    Just *** Exception: Prelude.undefined
    >>> head . fst <$> unsnoc (1 : 2 : undefined)
    Just 1

`unsnoc` is dual to `uncons`: for a finite list `xs`

    unsnoc xs = (\(hd, tl) -> (reverse tl, hd)) <$> uncons (reverse xs)