:: [a] -> Int -> Maybe a -package:safe -package:rio

A total variant of the list index function (!!).
[2,3,4] !? 1    == Just 3
[2,3,4] !? (-1) == Nothing
[]      !? 0    == Nothing
Safer version of !!, returns a Maybe. Get element from list using index value starting from `0`.
>>> [] !!? 0
Nothing
>>> ["a", "b", "c"] !!? 3
Nothing
>>> [1, 2, 3] !!? (-1)
Nothing
>>> ["a", "b", "c"] !!? 2
Just "c"
Lookup function (safe). O(min n index).
Safe version of (!!).
Array indexing with negative values allowed
O(1) Safe indexing.
A (!!) that fails using mzero
O(1) Indexing in a monad. The monad allows operations to be strict in the vector when necessary. Suppose vector copying is implemented like this:
copy mv v = ... write mv i (v ! i) ...
For lazy vectors, v ! i would not be evaluated which means that mv would unnecessarily retain a reference to v in each element written. With indexM, copying can be implemented like this instead:
copy mv v = ... do
x <- indexM v i
write mv i x
Here, no references to v are retained because indexing (but not the element) is evaluated eagerly.
O(1) Indexing in a monad, without bounds checks. See indexM for an explanation of why this is useful.
!!? with its arguments flipped. Get element from list using index value starting from `0`.
>>> maybeAt 0 []
Nothing
>>> maybeAt 3 ["a", "b", "c"]
Nothing
>>> maybeAt (-1) [1, 2, 3]
Nothing
>>> maybeAt 2 ["a", "b", "c"]
Just "c"
Deprecated: Use XMonad.Prelude.(!?) instead.
Safer version of !! -
O(n) Convert the first n elements of a list to a vector. It's expected that the supplied list will be exactly n elements long. As an optimization, this function allocates a buffer for n elements, which could be used for DoS-attacks by exhausting the memory if an attacker controls that parameter.
fromListN n xs = fromList (take n xs)

Examples

>>> import qualified Data.Vector as V

>>> V.fromListN 3 [1,2,3,4,5]
[1,2,3]

>>> V.fromListN 3 [1]
[1]
>>> fromReverseListN 3 [1,2,3] :: Data.Vector.Vector Int
[3,2,1]