Copyright | (c) The University of Glasgow 2001 |
---|---|

License | BSD-style (see the file libraries/base/LICENSE) |

Maintainer | libraries@haskell.org |

Stability | stable |

Portability | portable |

Safe Haskell | Trustworthy |

Language | Haskell2010 |

Operations on lists.

## Synopsis

- (++) :: [a] -> [a] -> [a]
- head :: HasCallStack => [a] -> a
- last :: HasCallStack => [a] -> a
- tail :: HasCallStack => [a] -> [a]
- init :: HasCallStack => [a] -> [a]
- uncons :: [a] -> Maybe (a, [a])
- unsnoc :: [a] -> Maybe ([a], a)
- singleton :: a -> [a]
- null :: [a] -> Bool
- length :: [a] -> Int
- map :: (a -> b) -> [a] -> [b]
- reverse :: [a] -> [a]
- intersperse :: a -> [a] -> [a]
- intercalate :: [a] -> [[a]] -> [a]
- transpose :: [[a]] -> [[a]]
- subsequences :: [a] -> [[a]]
- permutations :: [a] -> [[a]]
- foldl :: forall a b. (b -> a -> b) -> b -> [a] -> b
- foldl' :: forall a b. (b -> a -> b) -> b -> [a] -> b
- foldl1 :: HasCallStack => (a -> a -> a) -> [a] -> a
- foldl1' :: HasCallStack => (a -> a -> a) -> [a] -> a
- foldr :: (a -> b -> b) -> b -> [a] -> b
- foldr1 :: HasCallStack => (a -> a -> a) -> [a] -> a
- concat :: [[a]] -> [a]
- concatMap :: (a -> [b]) -> [a] -> [b]
- and :: [Bool] -> Bool
- or :: [Bool] -> Bool
- any :: (a -> Bool) -> [a] -> Bool
- all :: (a -> Bool) -> [a] -> Bool
- sum :: Num a => [a] -> a
- product :: Num a => [a] -> a
- maximum :: (Ord a, HasCallStack) => [a] -> a
- minimum :: (Ord a, HasCallStack) => [a] -> a
- scanl :: (b -> a -> b) -> b -> [a] -> [b]
- scanl' :: (b -> a -> b) -> b -> [a] -> [b]
- scanl1 :: (a -> a -> a) -> [a] -> [a]
- scanr :: (a -> b -> b) -> b -> [a] -> [b]
- scanr1 :: (a -> a -> a) -> [a] -> [a]
- mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
- mapAccumR :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
- iterate :: (a -> a) -> a -> [a]
- iterate' :: (a -> a) -> a -> [a]
- repeat :: a -> [a]
- replicate :: Int -> a -> [a]
- cycle :: HasCallStack => [a] -> [a]
- unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
- take :: Int -> [a] -> [a]
- drop :: Int -> [a] -> [a]
- splitAt :: Int -> [a] -> ([a], [a])
- takeWhile :: (a -> Bool) -> [a] -> [a]
- dropWhile :: (a -> Bool) -> [a] -> [a]
- dropWhileEnd :: (a -> Bool) -> [a] -> [a]
- span :: (a -> Bool) -> [a] -> ([a], [a])
- break :: (a -> Bool) -> [a] -> ([a], [a])
- stripPrefix :: Eq a => [a] -> [a] -> Maybe [a]
- group :: Eq a => [a] -> [[a]]
- inits :: [a] -> [[a]]
- tails :: [a] -> [[a]]
- isPrefixOf :: Eq a => [a] -> [a] -> Bool
- isSuffixOf :: Eq a => [a] -> [a] -> Bool
- isInfixOf :: Eq a => [a] -> [a] -> Bool
- elem :: Eq a => a -> [a] -> Bool
- notElem :: Eq a => a -> [a] -> Bool
- lookup :: Eq a => a -> [(a, b)] -> Maybe b
- find :: (a -> Bool) -> [a] -> Maybe a
- filter :: (a -> Bool) -> [a] -> [a]
- partition :: (a -> Bool) -> [a] -> ([a], [a])
- (!?) :: [a] -> Int -> Maybe a
- (!!) :: HasCallStack => [a] -> Int -> a
- elemIndex :: Eq a => a -> [a] -> Maybe Int
- elemIndices :: Eq a => a -> [a] -> [Int]
- findIndex :: (a -> Bool) -> [a] -> Maybe Int
- findIndices :: (a -> Bool) -> [a] -> [Int]
- zip :: [a] -> [b] -> [(a, b)]
- zip3 :: [a] -> [b] -> [c] -> [(a, b, c)]
- zip4 :: [a] -> [b] -> [c] -> [d] -> [(a, b, c, d)]
- zip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a, b, c, d, e)]
- zip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a, b, c, d, e, f)]
- zip7 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [(a, b, c, d, e, f, g)]
- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
- zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
- zipWith4 :: (a -> b -> c -> d -> e) -> [a] -> [b] -> [c] -> [d] -> [e]
- zipWith5 :: (a -> b -> c -> d -> e -> f) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f]
- zipWith6 :: (a -> b -> c -> d -> e -> f -> g) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g]
- zipWith7 :: (a -> b -> c -> d -> e -> f -> g -> h) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [h]
- unzip :: [(a, b)] -> ([a], [b])
- unzip3 :: [(a, b, c)] -> ([a], [b], [c])
- unzip4 :: [(a, b, c, d)] -> ([a], [b], [c], [d])
- unzip5 :: [(a, b, c, d, e)] -> ([a], [b], [c], [d], [e])
- unzip6 :: [(a, b, c, d, e, f)] -> ([a], [b], [c], [d], [e], [f])
- unzip7 :: [(a, b, c, d, e, f, g)] -> ([a], [b], [c], [d], [e], [f], [g])
- lines :: String -> [String]
- words :: String -> [String]
- unlines :: [String] -> String
- unwords :: [String] -> String
- nub :: Eq a => [a] -> [a]
- delete :: Eq a => a -> [a] -> [a]
- (\\) :: Eq a => [a] -> [a] -> [a]
- union :: Eq a => [a] -> [a] -> [a]
- intersect :: Eq a => [a] -> [a] -> [a]
- sort :: Ord a => [a] -> [a]
- sortOn :: Ord b => (a -> b) -> [a] -> [a]
- insert :: Ord a => a -> [a] -> [a]
- nubBy :: (a -> a -> Bool) -> [a] -> [a]
- deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a]
- deleteFirstsBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
- unionBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
- intersectBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
- groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
- sortBy :: (a -> a -> Ordering) -> [a] -> [a]
- insertBy :: (a -> a -> Ordering) -> a -> [a] -> [a]
- maximumBy :: (a -> a -> Ordering) -> [a] -> a
- minimumBy :: (a -> a -> Ordering) -> [a] -> a
- genericLength :: Num i => [a] -> i
- genericTake :: Integral i => i -> [a] -> [a]
- genericDrop :: Integral i => i -> [a] -> [a]
- genericSplitAt :: Integral i => i -> [a] -> ([a], [a])
- genericIndex :: Integral i => [a] -> i -> a
- genericReplicate :: Integral i => i -> a -> [a]

# Basic functions

(++) :: [a] -> [a] -> [a] infixr 5 Source #

`(++)`

appends two lists, i.e.,

[x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn] [x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...]

If the first list is not finite, the result is the first list.

#### Performance considerations

This function takes linear time in the number of elements of the
**first** list. Thus it is better to associate repeated
applications of `(++)`

to the right (which is the default behaviour):
`xs ++ (ys ++ zs)`

or simply `xs ++ ys ++ zs`

, but not `(xs ++ ys) ++ zs`

.
For the same reason `concat`

`=`

`foldr`

`(++)`

`[]`

has linear performance, while `foldl`

`(++)`

`[]`

is prone
to quadratic slowdown

#### Examples

`>>>`

[1,2,3,4,5,6]`[1, 2, 3] ++ [4, 5, 6]`

`>>>`

[1,2,3]`[] ++ [1, 2, 3]`

`>>>`

[3,2,1]`[3, 2, 1] ++ []`

head :: HasCallStack => [a] -> a Source #

Warning: This is a partial function, it throws an error on empty lists. Use pattern matching, `uncons`

or `listToMaybe`

instead. Consider refactoring to use Data.List.NonEmpty.

\(\mathcal{O}(1)\). Extract the first element of a list, which must be non-empty.

To disable the warning about partiality put `{-# OPTIONS_GHC -Wno-x-partial -Wno-unrecognised-warning-flags #-}`

at the top of the file. To disable it throughout a package put the same
options into `ghc-options`

section of Cabal file. To disable it in GHCi
put `:set -Wno-x-partial -Wno-unrecognised-warning-flags`

into `~/.ghci`

config file.
See also the migration guide.

##### Examples

`>>>`

1`head [1, 2, 3]`

`>>>`

1`head [1..]`

`>>>`

*** Exception: Prelude.head: empty list`head []`

last :: HasCallStack => [a] -> a Source #

\(\mathcal{O}(n)\). Extract the last element of a list, which must be finite and non-empty.

WARNING: This function is partial. Consider using `unsnoc`

instead.

#### Examples

`>>>`

3`last [1, 2, 3]`

`>>>`

* Hangs forever *`last [1..]`

`>>>`

*** Exception: Prelude.last: empty list`last []`

tail :: HasCallStack => [a] -> [a] Source #

Warning: This is a partial function, it throws an error on empty lists. Replace it with `drop`

1, or use pattern matching or `uncons`

instead. Consider refactoring to use Data.List.NonEmpty.

\(\mathcal{O}(1)\). Extract the elements after the head of a list, which must be non-empty.

To disable the warning about partiality put `{-# OPTIONS_GHC -Wno-x-partial -Wno-unrecognised-warning-flags #-}`

at the top of the file. To disable it throughout a package put the same
options into `ghc-options`

section of Cabal file. To disable it in GHCi
put `:set -Wno-x-partial -Wno-unrecognised-warning-flags`

into `~/.ghci`

config file.
See also the migration guide.

#### Examples

`>>>`

[2,3]`tail [1, 2, 3]`

`>>>`

[]`tail [1]`

`>>>`

*** Exception: Prelude.tail: empty list`tail []`

init :: HasCallStack => [a] -> [a] Source #

\(\mathcal{O}(n)\). Return all the elements of a list except the last one. The list must be non-empty.

WARNING: This function is partial. Consider using `unsnoc`

instead.

#### Examples

`>>>`

[1,2]`init [1, 2, 3]`

`>>>`

[]`init [1]`

`>>>`

*** Exception: Prelude.init: empty list`init []`

uncons :: [a] -> Maybe (a, [a]) Source #

\(\mathcal{O}(1)\). Decompose a list into its `head`

and `tail`

.

- If the list is empty, returns
`Nothing`

. - If the list is non-empty, returns

, where`Just`

(x, xs)`x`

is the`head`

of the list and`xs`

its`tail`

.

#### Examples

`>>>`

Nothing`uncons []`

`>>>`

Just (1,[])`uncons [1]`

`>>>`

Just (1,[2,3])`uncons [1, 2, 3]`

*Since: base-4.8.0.0*

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

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

and `last`

.

- If the list is empty, returns
`Nothing`

. - If the list is non-empty, returns

, where`Just`

(xs, x)`xs`

is the`init`

ial part of the list and`x`

is its`last`

element.

`unsnoc`

is dual to `uncons`

: for a finite list `xs`

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

#### Examples

`>>>`

Nothing`unsnoc []`

`>>>`

Just ([],1)`unsnoc [1]`

`>>>`

Just ([1,2],3)`unsnoc [1, 2, 3]`

#### Laziness

`>>>`

Just []`fst <$> unsnoc [undefined]`

`>>>`

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

`>>>`

Just 1`head . fst <$> unsnoc (1 : 2 : undefined)`

*Since: base-4.19.0.0*

singleton :: a -> [a] Source #

Construct a list from a single element.

#### Examples

`>>>`

[True]`singleton True`

`>>>`

[[1,2,3]]`singleton [1, 2, 3]`

`>>>`

"c"`singleton 'c'`

*Since: base-4.15.0.0*

\(\mathcal{O}(1)\). Test whether a list is empty.

`>>>`

True`null []`

`>>>`

False`null [1]`

`>>>`

False`null [1..]`

\(\mathcal{O}(n)\). `length`

returns the length of a finite list as an
`Int`

. It is an instance of the more general `genericLength`

, the
result type of which may be any kind of number.

`>>>`

0`length []`

`>>>`

3`length ['a', 'b', 'c']`

`>>>`

* Hangs forever *`length [1..]`

# List transformations

map :: (a -> b) -> [a] -> [b] Source #

\(\mathcal{O}(n)\). `map`

`f xs`

is the list obtained by applying `f`

to
each element of `xs`

, i.e.,

map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn] map f [x1, x2, ...] == [f x1, f x2, ...]

this means that `map id == id`

#### Examples

`>>>`

[2,3,4]`map (+1) [1, 2, 3]`

`>>>`

[1,2,3]`map id [1, 2, 3]`

`>>>`

[4,7,10]`map (\n -> 3 * n + 1) [1, 2, 3]`

reverse :: [a] -> [a] Source #

\(\mathcal{O}(n)\). `reverse`

`xs`

returns the elements of `xs`

in reverse order.
`xs`

must be finite.

#### Laziness

`reverse`

is lazy in its elements.

`>>>`

1`head (reverse [undefined, 1])`

`>>>`

*** Exception: Prelude.undefined`reverse (1 : 2 : undefined)`

#### Examples

`>>>`

[]`reverse []`

`>>>`

[42]`reverse [42]`

`>>>`

[7,5,2]`reverse [2,5,7]`

`>>>`

* Hangs forever *`reverse [1..]`

intersperse :: a -> [a] -> [a] Source #

\(\mathcal{O}(n)\). The `intersperse`

function takes an element and a list
and `intersperses' that element between the elements of the list.

#### Laziness

`intersperse`

has the following properties

`>>>`

"a"`take 1 (intersperse undefined ('a' : undefined))`

`>>>`

"a*** Exception: Prelude.undefined`take 2 (intersperse ',' ('a' : undefined))`

#### Examples

`>>>`

"a,b,c,d,e"`intersperse ',' "abcde"`

`>>>`

[3,1,4,1,5]`intersperse 1 [3, 4, 5]`

intercalate :: [a] -> [[a]] -> [a] Source #

`intercalate`

`xs xss`

is equivalent to `(`

.
It inserts the list `concat`

(`intersperse`

xs xss))`xs`

in between the lists in `xss`

and concatenates the
result.

#### Laziness

`intercalate`

has the following properties:

`>>>`

"Lorem"`take 5 (intercalate undefined ("Lorem" : undefined))`

`>>>`

"Lorem*** Exception: Prelude.undefined`take 6 (intercalate ", " ("Lorem" : undefined))`

#### Examples

`>>>`

"Lorem, ipsum, dolor"`intercalate ", " ["Lorem", "ipsum", "dolor"]`

`>>>`

[2,3,0,1,4,5,6,0,1]`intercalate [0, 1] [[2, 3], [4, 5, 6], []]`

`>>>`

[1,2,3]`intercalate [1, 2, 3] [[], []]`

transpose :: [[a]] -> [[a]] Source #

The `transpose`

function transposes the rows and columns of its argument.

#### Laziness

`transpose`

is lazy in its elements

`>>>`

["ab"]`take 1 (transpose ['a' : undefined, 'b' : undefined])`

#### Examples

`>>>`

[[1,4],[2,5],[3,6]]`transpose [[1,2,3],[4,5,6]]`

If some of the rows are shorter than the following rows, their elements are skipped:

`>>>`

[[10,20,30],[11,31],[32]]`transpose [[10,11],[20],[],[30,31,32]]`

For this reason the outer list must be finite; otherwise `transpose`

hangs:

`>>>`

* Hangs forever *`transpose (repeat [])`

subsequences :: [a] -> [[a]] Source #

The `subsequences`

function returns the list of all subsequences of the argument.

#### Laziness

`subsequences`

does not look ahead unless it must:

`>>>`

[[]]`take 1 (subsequences undefined)`

`>>>`

["","a"]`take 2 (subsequences ('a' : undefined))`

#### Examples

`>>>`

["","a","b","ab","c","ac","bc","abc"]`subsequences "abc"`

This function is productive on infinite inputs:

`>>>`

["","a","b","ab","c","ac","bc","abc"]`take 8 $ subsequences ['a'..]`

permutations :: [a] -> [[a]] Source #

The `permutations`

function returns the list of all permutations of the argument.

Note that the order of permutations is not lexicographic. It satisfies the following property:

map (take n) (take (product [1..n]) (permutations ([1..n] ++ undefined))) == permutations [1..n]

#### Laziness

The `permutations`

function is maximally lazy:
for each `n`

, the value of

starts with those permutations
that permute `permutations`

xs

and keep `take`

n xs

.`drop`

n xs

#### Examples

`>>>`

["abc","bac","cba","bca","cab","acb"]`permutations "abc"`

`>>>`

[[1,2],[2,1]]`permutations [1, 2]`

`>>>`

[[]]`permutations []`

This function is productive on infinite inputs:

`>>>`

["abc","bac","cba","bca","cab","acb"]`take 6 $ map (take 3) $ permutations ['a'..]`

# Reducing lists (folds)

foldl :: forall a b. (b -> a -> b) -> b -> [a] -> b Source #

`foldl`

, applied to a binary operator, a starting value (typically
the left-identity of the operator), and a list, reduces the list
using the binary operator, from left to right:

foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn

The list must be finite.

`>>>`

10`foldl (+) 0 [1..4]`

`>>>`

42`foldl (+) 42 []`

`>>>`

90`foldl (-) 100 [1..4]`

`>>>`

"dcbafoo"`foldl (\reversedString nextChar -> nextChar : reversedString) "foo" ['a', 'b', 'c', 'd']`

`>>>`

* Hangs forever *`foldl (+) 0 [1..]`

foldl1 :: HasCallStack => (a -> a -> a) -> [a] -> a Source #

`foldl1`

is a variant of `foldl`

that has no starting value argument,
and thus must be applied to non-empty lists. Note that unlike `foldl`

, the accumulated value must be of the same type as the list elements.

`>>>`

10`foldl1 (+) [1..4]`

`>>>`

*** Exception: Prelude.foldl1: empty list`foldl1 (+) []`

`>>>`

-8`foldl1 (-) [1..4]`

`>>>`

False`foldl1 (&&) [True, False, True, True]`

`>>>`

True`foldl1 (||) [False, False, True, True]`

`>>>`

* Hangs forever *`foldl1 (+) [1..]`

foldl1' :: HasCallStack => (a -> a -> a) -> [a] -> a Source #

A strict version of `foldl1`

.

foldr :: (a -> b -> b) -> b -> [a] -> b Source #

`foldr`

, applied to a binary operator, a starting value (typically
the right-identity of the operator), and a list, reduces the list
using the binary operator, from right to left:

foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)

foldr1 :: HasCallStack => (a -> a -> a) -> [a] -> a Source #

`foldr1`

is a variant of `foldr`

that has no starting value argument,
and thus must be applied to non-empty lists. Note that unlike `foldr`

, the accumulated value must be of the same type as the list elements.

`>>>`

10`foldr1 (+) [1..4]`

`>>>`

*** Exception: Prelude.foldr1: empty list`foldr1 (+) []`

`>>>`

-2`foldr1 (-) [1..4]`

`>>>`

False`foldr1 (&&) [True, False, True, True]`

`>>>`

True`foldr1 (||) [False, False, True, True]`

`>>>`

*** Exception: stack overflow`force $ foldr1 (+) [1..]`

## Special folds

concat :: [[a]] -> [a] Source #

Concatenate a list of lists.

#### Examples

`>>>`

[1,2,3,4,5,6]`concat [[1,2,3], [4,5], [6], []]`

`>>>`

[]`concat []`

`>>>`

[42]`concat [[42]]`

concatMap :: (a -> [b]) -> [a] -> [b] Source #

Map a function returning a list over a list and concatenate the results.
`concatMap`

can be seen as the composition of `concat`

and `map`

.

concatMap f xs == (concat . map f) xs

#### Examples

`>>>`

[]`concatMap (\i -> [-i,i]) []`

`>>>`

[-1,1,-2,2,-3,3]`concatMap (\i -> [-i, i]) [1, 2, 3]`

`>>>`

[0,0,0,2,2,2,4,4,4]`concatMap ('replicate' 3) [0, 2, 4]`

and :: [Bool] -> Bool Source #

`and`

returns the conjunction of a Boolean list. For the result to be
`True`

, the list must be finite; `False`

, however, results from a `False`

value at a finite index of a finite or infinite list.

#### Examples

`>>>`

True`and []`

`>>>`

True`and [True]`

`>>>`

False`and [False]`

`>>>`

False`and [True, True, False]`

`>>>`

False`and (False : repeat True) -- Infinite list [False,True,True,True,True,True,True...`

`>>>`

* Hangs forever *`and (repeat True)`

`or`

returns the disjunction of a Boolean list. For the result to be
`False`

, the list must be finite; `True`

, however, results from a `True`

value at a finite index of a finite or infinite list.

#### Examples

`>>>`

False`or []`

`>>>`

True`or [True]`

`>>>`

False`or [False]`

`>>>`

True`or [True, True, False]`

`>>>`

True`or (True : repeat False) -- Infinite list [True,False,False,False,False,False,False...`

`>>>`

* Hangs forever *`or (repeat False)`

any :: (a -> Bool) -> [a] -> Bool Source #

Applied to a predicate and a list, `any`

determines if any element
of the list satisfies the predicate. For the result to be
`False`

, the list must be finite; `True`

, however, results from a `True`

value for the predicate applied to an element at a finite index of a finite
or infinite list.

#### Examples

`>>>`

False`any (> 3) []`

`>>>`

False`any (> 3) [1,2]`

`>>>`

True`any (> 3) [1,2,3,4,5]`

`>>>`

True`any (> 3) [1..]`

`>>>`

* Hangs forever *`any (> 3) [0, -1..]`

all :: (a -> Bool) -> [a] -> Bool Source #

Applied to a predicate and a list, `all`

determines if all elements
of the list satisfy the predicate. For the result to be
`True`

, the list must be finite; `False`

, however, results from a `False`

value for the predicate applied to an element at a finite index of a finite
or infinite list.

#### Examples

`>>>`

True`all (> 3) []`

`>>>`

False`all (> 3) [1,2]`

`>>>`

False`all (> 3) [1,2,3,4,5]`

`>>>`

False`all (> 3) [1..]`

`>>>`

* Hangs forever *`all (> 3) [4..]`

sum :: Num a => [a] -> a Source #

The `sum`

function computes the sum of a finite list of numbers.

`>>>`

0`sum []`

`>>>`

42`sum [42]`

`>>>`

55`sum [1..10]`

`>>>`

7.8`sum [4.1, 2.0, 1.7]`

`>>>`

* Hangs forever *`sum [1..]`

product :: Num a => [a] -> a Source #

The `product`

function computes the product of a finite list of numbers.

`>>>`

1`product []`

`>>>`

42`product [42]`

`>>>`

3628800`product [1..10]`

`>>>`

13.939999999999998`product [4.1, 2.0, 1.7]`

`>>>`

* Hangs forever *`product [1..]`

maximum :: (Ord a, HasCallStack) => [a] -> a Source #

`maximum`

returns the maximum value from a list,
which must be non-empty, finite, and of an ordered type.
It is a special case of `maximumBy`

, which allows the
programmer to supply their own comparison function.

`>>>`

*** Exception: Prelude.maximum: empty list`maximum []`

`>>>`

42`maximum [42]`

`>>>`

55`maximum [55, -12, 7, 0, -89]`

`>>>`

* Hangs forever *`maximum [1..]`

minimum :: (Ord a, HasCallStack) => [a] -> a Source #

`minimum`

returns the minimum value from a list,
which must be non-empty, finite, and of an ordered type.
It is a special case of `minimumBy`

, which allows the
programmer to supply their own comparison function.

`>>>`

*** Exception: Prelude.minimum: empty list`minimum []`

`>>>`

42`minimum [42]`

`>>>`

-89`minimum [55, -12, 7, 0, -89]`

`>>>`

* Hangs forever *`minimum [1..]`

# Building lists

## Scans

scanl :: (b -> a -> b) -> b -> [a] -> [b] Source #

\(\mathcal{O}(n)\). `scanl`

is similar to `foldl`

, but returns a list of
successive reduced values from the left:

scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]

Note that

last (scanl f z xs) == foldl f z xs

#### Examples

`>>>`

[0,1,3,6,10]`scanl (+) 0 [1..4]`

`>>>`

[42]`scanl (+) 42 []`

`>>>`

[100,99,97,94,90]`scanl (-) 100 [1..4]`

`>>>`

["foo","afoo","bafoo","cbafoo","dcbafoo"]`scanl (\reversedString nextChar -> nextChar : reversedString) "foo" ['a', 'b', 'c', 'd']`

`>>>`

[0,1,3,6,10,15,21,28,36,45]`take 10 (scanl (+) 0 [1..])`

`>>>`

"a"`take 1 (scanl undefined 'a' undefined)`

scanl1 :: (a -> a -> a) -> [a] -> [a] Source #

\(\mathcal{O}(n)\). `scanl1`

is a variant of `scanl`

that has no starting
value argument:

scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]

#### Examples

`>>>`

[1,3,6,10]`scanl1 (+) [1..4]`

`>>>`

[]`scanl1 (+) []`

`>>>`

[1,-1,-4,-8]`scanl1 (-) [1..4]`

`>>>`

[True,False,False,False]`scanl1 (&&) [True, False, True, True]`

`>>>`

[False,False,True,True]`scanl1 (||) [False, False, True, True]`

`>>>`

[1,3,6,10,15,21,28,36,45,55]`take 10 (scanl1 (+) [1..])`

`>>>`

"a"`take 1 (scanl1 undefined ('a' : undefined))`

scanr :: (a -> b -> b) -> b -> [a] -> [b] Source #

\(\mathcal{O}(n)\). `scanr`

is the right-to-left dual of `scanl`

. Note that the order of parameters on the accumulating function are reversed compared to `scanl`

.
Also note that

head (scanr f z xs) == foldr f z xs.

#### Examples

`>>>`

[10,9,7,4,0]`scanr (+) 0 [1..4]`

`>>>`

[42]`scanr (+) 42 []`

`>>>`

[98,-97,99,-96,100]`scanr (-) 100 [1..4]`

`>>>`

["abcdfoo","bcdfoo","cdfoo","dfoo","foo"]`scanr (\nextChar reversedString -> nextChar : reversedString) "foo" ['a', 'b', 'c', 'd']`

`>>>`

*** Exception: stack overflow`force $ scanr (+) 0 [1..]`

scanr1 :: (a -> a -> a) -> [a] -> [a] Source #

\(\mathcal{O}(n)\). `scanr1`

is a variant of `scanr`

that has no starting
value argument.

#### Examples

`>>>`

[10,9,7,4]`scanr1 (+) [1..4]`

`>>>`

[]`scanr1 (+) []`

`>>>`

[-2,3,-1,4]`scanr1 (-) [1..4]`

`>>>`

[False,False,True,True]`scanr1 (&&) [True, False, True, True]`

`>>>`

[True,True,False,False]`scanr1 (||) [True, True, False, False]`

`>>>`

*** Exception: stack overflow`force $ scanr1 (+) [1..]`

## Accumulating maps

mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) Source #

The `mapAccumL`

function behaves like a combination of `map`

and
`foldl`

; it applies a function to each element of a list, passing
an accumulating parameter from left to right, and returning a final
value of this accumulator together with the new list.

`mapAccumL`

does not force accumulator if it is unused:

`>>>`

"a"`take 1 (snd (mapAccumL (\_ x -> (undefined, x)) undefined ('a' : undefined)))`

## Infinite lists

iterate :: (a -> a) -> a -> [a] Source #

`iterate`

`f x`

returns an infinite list of repeated applications
of `f`

to `x`

:

iterate f x == [x, f x, f (f x), ...]

#### Laziness

Note that `iterate`

is lazy, potentially leading to thunk build-up if
the consumer doesn't force each iterate. See `iterate'`

for a strict
variant of this function.

`>>>`

[42]`take 1 $ iterate undefined 42`

#### Examples

`>>>`

[True,False,True,False,True,False,True,False,True,False]`take 10 $ iterate not True`

`>>>`

[42,45,48,51,54,57,60,63,66,69]`take 10 $ iterate (+3) 42`

`iterate id == `

:`repeat`

`>>>`

[1,1,1,1,1,1,1,1,1,1]`take 10 $ iterate id 1`

`repeat`

`x`

is an infinite list, with `x`

the value of every element.

#### Examples

`>>>`

[17,17,17,17,17,17,17,17,17, 17]`take 10 $ repeat 17`

`>>>`

[*** Exception: Prelude.undefined`repeat undefined`

replicate :: Int -> a -> [a] Source #

`replicate`

`n x`

is a list of length `n`

with `x`

the value of
every element.
It is an instance of the more general `genericReplicate`

,
in which `n`

may be of any integral type.

#### Examples

`>>>`

[]`replicate 0 True`

`>>>`

[]`replicate (-1) True`

`>>>`

[True,True,True,True]`replicate 4 True`

cycle :: HasCallStack => [a] -> [a] Source #

`cycle`

ties a finite list into a circular one, or equivalently,
the infinite repetition of the original list. It is the identity
on infinite lists.

#### Examples

`>>>`

*** Exception: Prelude.cycle: empty list`cycle []`

`>>>`

[42,42,42,42,42,42,42,42,42,42]`take 10 (cycle [42])`

`>>>`

[2,5,7,2,5,7,2,5,7,2]`take 10 (cycle [2, 5, 7])`

`>>>`

[42]`take 1 (cycle (42 : undefined))`

## Unfolding

unfoldr :: (b -> Maybe (a, b)) -> b -> [a] Source #

The `unfoldr`

function is a `dual' to `foldr`

: while `foldr`

reduces a list to a summary value, `unfoldr`

builds a list from
a seed value. The function takes the element and returns `Nothing`

if it is done producing the list or returns `Just`

`(a,b)`

, in which
case, `a`

is a prepended to the list and `b`

is used as the next
element in a recursive call. For example,

iterate f == unfoldr (\x -> Just (x, f x))

In some cases, `unfoldr`

can undo a `foldr`

operation:

unfoldr f' (foldr f z xs) == xs

if the following holds:

f' (f x y) = Just (x,y) f' z = Nothing

#### Laziness

`>>>`

"a"`take 1 (unfoldr (\x -> Just (x, undefined)) 'a')`

#### Examples

`>>>`

[10,9,8,7,6,5,4,3,2,1]`unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10`

`>>>`

[0,1,1,2,3,5,8,13,21,54]`take 10 $ unfoldr (\(x, y) -> Just (x, (y, x + y))) (0, 1)`

# Sublists

## Extracting sublists

take :: Int -> [a] -> [a] Source #

`take`

`n`

, applied to a list `xs`

, returns the prefix of `xs`

of length `n`

, or `xs`

itself if `n >= `

.`length`

xs

It is an instance of the more general `genericTake`

,
in which `n`

may be of any integral type.

#### Laziness

`>>>`

[]`take 0 undefined`

`>>>`

[1,2]`take 2 (1 : 2 : undefined)`

#### Examples

`>>>`

"Hello"`take 5 "Hello World!"`

`>>>`

[1,2,3]`take 3 [1,2,3,4,5]`

`>>>`

[1,2]`take 3 [1,2]`

`>>>`

[]`take 3 []`

`>>>`

[]`take (-1) [1,2]`

`>>>`

[]`take 0 [1,2]`

drop :: Int -> [a] -> [a] Source #

`drop`

`n xs`

returns the suffix of `xs`

after the first `n`

elements, or `[]`

if `n >= `

.`length`

xs

It is an instance of the more general `genericDrop`

,
in which `n`

may be of any integral type.

#### Examples

`>>>`

"World!"`drop 6 "Hello World!"`

`>>>`

[4,5]`drop 3 [1,2,3,4,5]`

`>>>`

[]`drop 3 [1,2]`

`>>>`

[]`drop 3 []`

`>>>`

[1,2]`drop (-1) [1,2]`

`>>>`

[1,2]`drop 0 [1,2]`

splitAt :: Int -> [a] -> ([a], [a]) Source #

`splitAt`

`n xs`

returns a tuple where first element is `xs`

prefix of
length `n`

and second element is the remainder of the list:

`splitAt`

is an instance of the more general `genericSplitAt`

,
in which `n`

may be of any integral type.

#### Laziness

It is equivalent to `(`

unless `take`

n xs, `drop`

n xs)`n`

is `_|_`

:
`splitAt _|_ xs = _|_`

, not `(_|_, _|_)`

).

The first component of the tuple is produced lazily:

`>>>`

[]`fst (splitAt 0 undefined)`

`>>>`

[1]`take 1 (fst (splitAt 10 (1 : undefined)))`

#### Examples

`>>>`

("Hello ","World!")`splitAt 6 "Hello World!"`

`>>>`

([1,2,3],[4,5])`splitAt 3 [1,2,3,4,5]`

`>>>`

([1],[2,3])`splitAt 1 [1,2,3]`

`>>>`

([1,2,3],[])`splitAt 3 [1,2,3]`

`>>>`

([1,2,3],[])`splitAt 4 [1,2,3]`

`>>>`

([],[1,2,3])`splitAt 0 [1,2,3]`

`>>>`

([],[1,2,3])`splitAt (-1) [1,2,3]`

takeWhile :: (a -> Bool) -> [a] -> [a] Source #

`takeWhile`

, applied to a predicate `p`

and a list `xs`

, returns the
longest prefix (possibly empty) of `xs`

of elements that satisfy `p`

.

#### Laziness

`>>>`

*** Exception: Prelude.undefined`takeWhile (const False) undefined`

`>>>`

[]`takeWhile (const False) (undefined : undefined)`

`>>>`

[1]`take 1 (takeWhile (const True) (1 : undefined))`

#### Examples

`>>>`

[1,2]`takeWhile (< 3) [1,2,3,4,1,2,3,4]`

`>>>`

[1,2,3]`takeWhile (< 9) [1,2,3]`

`>>>`

[]`takeWhile (< 0) [1,2,3]`

dropWhileEnd :: (a -> Bool) -> [a] -> [a] Source #

The `dropWhileEnd`

function drops the largest suffix of a list
in which the given predicate holds for all elements.

#### Laziness

This function is lazy in spine, but strict in elements,
which makes it different from `reverse`

`.`

`dropWhile`

`p`

`.`

`reverse`

,
which is strict in spine, but lazy in elements. For instance:

`>>>`

[1]`take 1 (dropWhileEnd (< 0) (1 : undefined))`

`>>>`

*** Exception: Prelude.undefined`take 1 (reverse $ dropWhile (< 0) $ reverse (1 : undefined))`

but on the other hand

`>>>`

*** Exception: Prelude.undefined`last (dropWhileEnd (< 0) [undefined, 1])`

`>>>`

1`last (reverse $ dropWhile (< 0) $ reverse [undefined, 1])`

#### Examples

`>>>`

"foo"`dropWhileEnd isSpace "foo\n"`

`>>>`

"foo bar"`dropWhileEnd isSpace "foo bar"`

`>>>`

[1,2,3,4,5,6,7,8,9,10]`dropWhileEnd (> 10) [1..20]`

*Since: base-4.5.0.0*

span :: (a -> Bool) -> [a] -> ([a], [a]) Source #

`span`

, applied to a predicate `p`

and a list `xs`

, returns a tuple where
first element is the longest prefix (possibly empty) of `xs`

of elements that
satisfy `p`

and second element is the remainder of the list:

`span`

`p xs`

is equivalent to `(`

, even if `takeWhile`

p xs, `dropWhile`

p xs)`p`

is `_|_`

.

#### Laziness

`>>>`

([],[])`span undefined []`

`>>>`

*** Exception: Prelude.undefined`fst (span (const False) undefined)`

`>>>`

[]`fst (span (const False) (undefined : undefined))`

`>>>`

[1]`take 1 (fst (span (const True) (1 : undefined)))`

`span`

produces the first component of the tuple lazily:

`>>>`

[1,2,3,4,5,6,7,8,9,10]`take 10 (fst (span (const True) [1..]))`

#### Examples

`>>>`

([1,2],[3,4,1,2,3,4])`span (< 3) [1,2,3,4,1,2,3,4]`

`>>>`

([1,2,3],[])`span (< 9) [1,2,3]`

`>>>`

([],[1,2,3])`span (< 0) [1,2,3]`

break :: (a -> Bool) -> [a] -> ([a], [a]) Source #

`break`

, applied to a predicate `p`

and a list `xs`

, returns a tuple where
first element is longest prefix (possibly empty) of `xs`

of elements that
*do not satisfy* `p`

and second element is the remainder of the list:

`break`

`p`

is equivalent to

and consequently to `span`

(`not`

. p)`(`

,
even if `takeWhile`

(`not`

. p) xs, `dropWhile`

(`not`

. p) xs)`p`

is `_|_`

.

#### Laziness

`>>>`

([],[])`break undefined []`

`>>>`

*** Exception: Prelude.undefined`fst (break (const True) undefined)`

`>>>`

[]`fst (break (const True) (undefined : undefined))`

`>>>`

[1]`take 1 (fst (break (const False) (1 : undefined)))`

`break`

produces the first component of the tuple lazily:

`>>>`

[1,2,3,4,5,6,7,8,9,10]`take 10 (fst (break (const False) [1..]))`

#### Examples

`>>>`

([1,2,3],[4,1,2,3,4])`break (> 3) [1,2,3,4,1,2,3,4]`

`>>>`

([],[1,2,3])`break (< 9) [1,2,3]`

`>>>`

([1,2,3],[])`break (> 9) [1,2,3]`

stripPrefix :: Eq a => [a] -> [a] -> Maybe [a] Source #

\(\mathcal{O}(\min(m,n))\). The `stripPrefix`

function drops the given
prefix from a list. It returns `Nothing`

if the list did not start with the
prefix given, or `Just`

the list after the prefix, if it does.

##### Examples

`>>>`

Just "bar"`stripPrefix "foo" "foobar"`

`>>>`

Just ""`stripPrefix "foo" "foo"`

`>>>`

Nothing`stripPrefix "foo" "barfoo"`

`>>>`

Nothing`stripPrefix "foo" "barfoobaz"`

group :: Eq a => [a] -> [[a]] Source #

The `group`

function takes a list and returns a list of lists such
that the concatenation of the result is equal to the argument. Moreover,
each sublist in the result is non-empty, all elements are equal to the
first one, and consecutive equal elements of the input end up in the
same element of the output list.

`group`

is a special case of `groupBy`

, which allows the programmer to supply
their own equality test.

It's often preferable to use `Data.List.NonEmpty.`

`group`

,
which provides type-level guarantees of non-emptiness of inner lists.
A common idiom to squash repeating elements `map`

`head`

`.`

`group`

is better served by
`map`

`Data.List.NonEmpty.`

`head`

`.`

`Data.List.NonEmpty.`

`group`

because it avoids partial functions.

#### Examples

`>>>`

["M","i","ss","i","ss","i","pp","i"]`group "Mississippi"`

`>>>`

[[1,1,1],[2,2],[3],[4],[5,5]]`group [1, 1, 1, 2, 2, 3, 4, 5, 5]`

inits :: [a] -> [[a]] Source #

The `inits`

function returns all initial segments of the argument,
shortest first.

`inits`

is semantically equivalent to

,
but under the hood uses a queue to amortize costs of `map`

`reverse`

. `scanl`

(`flip`

(:)) []`reverse`

.

#### Laziness

Note that `inits`

has the following strictness property:
`inits (xs ++ _|_) = inits xs ++ _|_`

In particular,
`inits _|_ = [] : _|_`

#### Examples

`>>>`

["","a","ab","abc"]`inits "abc"`

`>>>`

[[]]`inits []`

inits is productive on infinite lists:

`>>>`

[[],[1],[1,2],[1,2,3],[1,2,3,4]]`take 5 $ inits [1..]`

tails :: [a] -> [[a]] Source #

\(\mathcal{O}(n)\). The `tails`

function returns all final segments of the
argument, longest first.

#### Laziness

Note that `tails`

has the following strictness property:
`tails _|_ = _|_ : _|_`

`>>>`

[*** Exception: Prelude.undefined`tails undefined`

`>>>`

[[1, 2], [2], []]`drop 1 (tails [undefined, 1, 2])`

#### Examples

`>>>`

["abc","bc","c",""]`tails "abc"`

`>>>`

[[1,2,3],[2,3],[3],[]]`tails [1, 2, 3]`

`>>>`

[[]]`tails []`

## Predicates

isPrefixOf :: Eq a => [a] -> [a] -> Bool Source #

\(\mathcal{O}(\min(m,n))\). The `isPrefixOf`

function takes two lists and
returns `True`

iff the first list is a prefix of the second.

#### Examples

`>>>`

True`"Hello" `isPrefixOf` "Hello World!"`

`>>>`

False`"Hello" `isPrefixOf` "Wello Horld!"`

For the result to be `True`

, the first list must be finite;
`False`

, however, results from any mismatch:

`>>>`

False`[0..] `isPrefixOf` [1..]`

`>>>`

False`[0..] `isPrefixOf` [0..99]`

`>>>`

True`[0..99] `isPrefixOf` [0..]`

`>>>`

* Hangs forever *`[0..] `isPrefixOf` [0..]`

`isPrefixOf`

shortcuts when the first argument is empty:

`>>>`

True`isPrefixOf [] undefined`

isSuffixOf :: Eq a => [a] -> [a] -> Bool Source #

The `isSuffixOf`

function takes two lists and returns `True`

iff
the first list is a suffix of the second.

#### Examples

`>>>`

True`"ld!" `isSuffixOf` "Hello World!"`

`>>>`

False`"World" `isSuffixOf` "Hello World!"`

The second list must be finite; however the first list may be infinite:

`>>>`

False`[0..] `isSuffixOf` [0..99]`

`>>>`

* Hangs forever *`[0..99] `isSuffixOf` [0..]`

isInfixOf :: Eq a => [a] -> [a] -> Bool Source #

The `isInfixOf`

function takes two lists and returns `True`

iff the first list is contained, wholly and intact,
anywhere within the second.

#### Examples

`>>>`

True`isInfixOf "Haskell" "I really like Haskell."`

`>>>`

False`isInfixOf "Ial" "I really like Haskell."`

For the result to be `True`

, the first list must be finite;
for the result to be `False`

, the second list must be finite:

`>>>`

True`[20..50] `isInfixOf` [0..]`

`>>>`

False`[0..] `isInfixOf` [20..50]`

`>>>`

* Hangs forever *`[0..] `isInfixOf` [0..]`

# Searching lists

## Searching by equality

elem :: Eq a => a -> [a] -> Bool infix 4 Source #

`elem`

is the list membership predicate, usually written in infix form,
e.g., `x `elem` xs`

. For the result to be
`False`

, the list must be finite; `True`

, however, results from an element
equal to `x`

found at a finite index of a finite or infinite list.

#### Examples

`>>>`

False`3 `elem` []`

`>>>`

False`3 `elem` [1,2]`

`>>>`

True`3 `elem` [1,2,3,4,5]`

`>>>`

True`3 `elem` [1..]`

`>>>`

* Hangs forever *`3 `elem` [4..]`

## Searching with a predicate

find :: (a -> Bool) -> [a] -> Maybe a Source #

The `find`

function takes a predicate and a list and returns the
first element in the list matching the predicate, or `Nothing`

if
there is no such element.
For the result to be `Nothing`

, the list must be finite.

#### Examples

`>>>`

Just 5`find (> 4) [1..]`

`>>>`

Nothing`find (< 0) [1..10]`

`>>>`

Just "marcus"`find ('a' `elem`) ["john", "marcus", "paul"]`

filter :: (a -> Bool) -> [a] -> [a] Source #

\(\mathcal{O}(n)\). `filter`

, applied to a predicate and a list, returns
the list of those elements that satisfy the predicate; i.e.,

filter p xs = [ x | x <- xs, p x]

#### Examples

`>>>`

[1,3]`filter odd [1, 2, 3]`

`>>>`

["Hello","World"]`filter (\l -> length l > 3) ["Hello", ", ", "World", "!"]`

`>>>`

[1,2,4,2,1]`filter (/= 3) [1, 2, 3, 4, 3, 2, 1]`

partition :: (a -> Bool) -> [a] -> ([a], [a]) Source #

The `partition`

function takes a predicate and a list, and returns
the pair of lists of elements which do and do not satisfy the
predicate, respectively; i.e.,

partition p xs == (filter p xs, filter (not . p) xs)

#### Examples

`>>>`

("eoo","Hll Wrld!")`partition (`elem` "aeiou") "Hello World!"`

`>>>`

([2,4,6,8,10],[1,3,5,7,9])`partition even [1..10]`

`>>>`

([1,2,3,4],[5,6,7,8,9,10])`partition (< 5) [1..10]`

# Indexing lists

These functions treat a list `xs`

as an indexed collection,
with indices ranging from 0 to

.`length`

xs - 1

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

List index (subscript) operator, starting from 0. Returns `Nothing`

if the index is out of bounds

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

operator.

WARNING: This function takes linear time in the index.

#### Examples

`>>>`

Just 'a'`['a', 'b', 'c'] !? 0`

`>>>`

Just 'c'`['a', 'b', 'c'] !? 2`

`>>>`

Nothing`['a', 'b', 'c'] !? 3`

`>>>`

Nothing`['a', 'b', 'c'] !? (-1)`

(!!) :: HasCallStack => [a] -> Int -> a infixl 9 Source #

List index (subscript) operator, starting from 0.
It is an instance of the more general `genericIndex`

,
which takes an index of any integral type.

WARNING: This function is partial, and should only be used if you are
sure that the indexing will not fail. Otherwise, use `!?`

.

WARNING: This function takes linear time in the index.

#### Examples

`>>>`

'a'`['a', 'b', 'c'] !! 0`

`>>>`

'c'`['a', 'b', 'c'] !! 2`

`>>>`

*** Exception: Prelude.!!: index too large`['a', 'b', 'c'] !! 3`

`>>>`

*** Exception: Prelude.!!: negative index`['a', 'b', 'c'] !! (-1)`

elemIndex :: Eq a => a -> [a] -> Maybe Int Source #

The `elemIndex`

function returns the index of the first element
in the given list which is equal (by `==`

) to the query element,
or `Nothing`

if there is no such element.
For the result to be `Nothing`

, the list must be finite.

#### Examples

`>>>`

Just 4`elemIndex 4 [0..]`

`>>>`

Nothing`elemIndex 'o' "haskell"`

`>>>`

* hangs forever *`elemIndex 0 [1..]`

elemIndices :: Eq a => a -> [a] -> [Int] Source #

The `elemIndices`

function extends `elemIndex`

, by returning the
indices of all elements equal to the query element, in ascending order.

#### Examples

`>>>`

[4,7]`elemIndices 'o' "Hello World"`

`>>>`

[0,3]`elemIndices 1 [1, 2, 3, 1, 2, 3]`

findIndex :: (a -> Bool) -> [a] -> Maybe Int Source #

The `findIndex`

function takes a predicate and a list and returns
the index of the first element in the list satisfying the predicate,
or `Nothing`

if there is no such element.
For the result to be `Nothing`

, the list must be finite.

#### Examples

`>>>`

Just 5`findIndex isSpace "Hello World!"`

`>>>`

Nothing`findIndex odd [0, 2, 4, 6]`

`>>>`

Just 1`findIndex even [1..]`

`>>>`

* hangs forever *`findIndex odd [0, 2 ..]`

findIndices :: (a -> Bool) -> [a] -> [Int] Source #

The `findIndices`

function extends `findIndex`

, by returning the
indices of all elements satisfying the predicate, in ascending order.

#### Examples

`>>>`

[1,4,7]`findIndices (`elem` "aeiou") "Hello World!"`

`>>>`

[1,3]`findIndices (\l -> length l > 3) ["a", "bcde", "fgh", "ijklmnop"]`

# Zipping and unzipping lists

zip :: [a] -> [b] -> [(a, b)] Source #

\(\mathcal{O}(\min(m,n))\). `zip`

takes two lists and returns a list of
corresponding pairs.

`zip`

is right-lazy:

`>>>`

[]`zip [] undefined`

`>>>`

*** Exception: Prelude.undefined ...`zip undefined []`

`zip`

is capable of list fusion, but it is restricted to its
first list argument and its resulting list.

#### Examples

`>>>`

[(1,'a'),(2,'b'),(3,'c')]`zip [1, 2, 3] ['a', 'b', 'c']`

If one input list is shorter than the other, excess elements of the longer list are discarded, even if one of the lists is infinite:

`>>>`

[(1,'a')]`zip [1] ['a', 'b']`

`>>>`

[(1,'a')]`zip [1, 2] ['a']`

`>>>`

[]`zip [] [1..]`

`>>>`

[]`zip [1..] []`

zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] Source #

\(\mathcal{O}(\min(m,n))\). `zipWith`

generalises `zip`

by zipping with the
function given as the first argument, instead of a tupling function.

zipWith (,) xs ys == zip xs ys zipWith f [x1,x2,x3..] [y1,y2,y3..] == [f x1 y1, f x2 y2, f x3 y3..]

`zipWith`

is right-lazy:

`>>>`

`let f = undefined`

`>>>`

[]`zipWith f [] undefined`

`zipWith`

is capable of list fusion, but it is restricted to its
first list argument and its resulting list.

#### Examples

zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d] Source #

\(\mathcal{O}(\min(l,m,n))\). The `zipWith3`

function takes a function which combines three
elements, as well as three lists and returns a list of the function applied
to corresponding elements, analogous to `zipWith`

.
It is capable of list fusion, but it is restricted to its
first list argument and its resulting list.

zipWith3 (,,) xs ys zs == zip3 xs ys zs zipWith3 f [x1,x2,x3..] [y1,y2,y3..] [z1,z2,z3..] == [f x1 y1 z1, f x2 y2 z2, f x3 y3 z3..]

#### Examples

`>>>`

["1ax","2by","3cz"]`zipWith3 (\x y z -> [x, y, z]) "123" "abc" "xyz"`

`>>>`

[11,18,27]`zipWith3 (\x y z -> (x * y) + z) [1, 2, 3] [4, 5, 6] [7, 8, 9]`

zipWith6 :: (a -> b -> c -> d -> e -> f -> g) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] Source #

zipWith7 :: (a -> b -> c -> d -> e -> f -> g -> h) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [h] Source #

unzip :: [(a, b)] -> ([a], [b]) Source #

`unzip`

transforms a list of pairs into a list of first components
and a list of second components.

#### Examples

`>>>`

([],[])`unzip []`

`>>>`

([1,2],"ab")`unzip [(1, 'a'), (2, 'b')]`

# Special lists

## Functions on strings

lines :: String -> [String] Source #

Splits the argument into a list of *lines* stripped of their terminating
`\n`

characters. The `\n`

terminator is optional in a final non-empty
line of the argument string.

When the argument string is empty, or ends in a `\n`

character, it can be
recovered by passing the result of `lines`

to the `unlines`

function.
Otherwise, `unlines`

appends the missing terminating `\n`

. This makes
`unlines . lines`

*idempotent*:

(unlines . lines) . (unlines . lines) = (unlines . lines)

#### Examples

`>>>`

[]`lines "" -- empty input contains no lines`

`>>>`

[""]`lines "\n" -- single empty line`

`>>>`

["one"]`lines "one" -- single unterminated line`

`>>>`

["one"]`lines "one\n" -- single non-empty line`

`>>>`

["one",""]`lines "one\n\n" -- second line is empty`

`>>>`

["one","two"]`lines "one\ntwo" -- second line is unterminated`

`>>>`

["one","two"]`lines "one\ntwo\n" -- two non-empty lines`

## "Set" operations

nub :: Eq a => [a] -> [a] Source #

\(\mathcal{O}(n^2)\). The `nub`

function removes duplicate elements from a
list. In particular, it keeps only the first occurrence of each element. (The
name `nub`

means `essence'.) It is a special case of `nubBy`

, which allows
the programmer to supply their own equality test.

If there exists `instance Ord a`

, it's faster to use `nubOrd`

from the `containers`

package
(link to the latest online documentation),
which takes only \(\mathcal{O}(n \log d)\) time where `d`

is the number of
distinct elements in the list.

Another approach to speed up `nub`

is to use
`map`

`Data.List.NonEmpty.`

`head`

. `Data.List.NonEmpty.`

`group`

. `sort`

,
which takes \(\mathcal{O}(n \log n)\) time, requires `instance Ord a`

and doesn't
preserve the order.

#### Examples

`>>>`

[1,2,3,4,5]`nub [1,2,3,4,3,2,1,2,4,3,5]`

`>>>`

"helo, wrd!"`nub "hello, world!"`

delete :: Eq a => a -> [a] -> [a] Source #

\(\mathcal{O}(n)\). `delete`

`x`

removes the first occurrence of `x`

from
its list argument.

It is a special case of `deleteBy`

, which allows the programmer to
supply their own equality test.

#### Examples

`>>>`

"bnana"`delete 'a' "banana"`

`>>>`

["haskell","is","awesome"]`delete "not" ["haskell", "is", "not", "awesome"]`

(\\) :: Eq a => [a] -> [a] -> [a] infix 5 Source #

The `\\`

function is list difference (non-associative).
In the result of `xs`

`\\`

`ys`

, the first occurrence of each element of
`ys`

in turn (if any) has been removed from `xs`

. Thus
`(xs ++ ys) \\ xs == ys`

.

It is a special case of `deleteFirstsBy`

, which allows the programmer
to supply their own equality test.

#### Examples

`>>>`

"Hoorld!"`"Hello World!" \\ "ell W"`

The second list must be finite, but the first may be infinite.

`>>>`

[0,1,5,6,7]`take 5 ([0..] \\ [2..4])`

`>>>`

* Hangs forever *`take 5 ([0..] \\ [2..])`

union :: Eq a => [a] -> [a] -> [a] Source #

The `union`

function returns the list union of the two lists.
It is a special case of `unionBy`

, which allows the programmer to supply
their own equality test.

#### Examples

`>>>`

"dogcw"`"dog" `union` "cow"`

If equal elements are present in both lists, an element from the first list will be used. If the second list contains equal elements, only the first one will be retained:

`>>>`

`import Data.Semigroup(Arg(..))`

`>>>`

[Arg () "dog"]`union [Arg () "dog"] [Arg () "cow"]`

`>>>`

[Arg () "dog"]`union [] [Arg () "dog", Arg () "cow"]`

However if the first list contains duplicates, so will the result:

`>>>`

"cootduk"`"coot" `union` "duck"`

`>>>`

"duckot"`"duck" `union` "coot"`

`union`

is productive even if both arguments are infinite.

`>>>`

[0,2,4,6,8,10,12..`[0, 2 ..] `union` [1, 3 ..]`

intersect :: Eq a => [a] -> [a] -> [a] Source #

The `intersect`

function takes the list intersection of two lists.
It is a special case of `intersectBy`

, which allows the programmer to
supply their own equality test.

##### Examples

`>>>`

[2,4]`[1,2,3,4] `intersect` [2,4,6,8]`

If equal elements are present in both lists, an element from the first list will be used, and all duplicates from the second list quashed:

`>>>`

`import Data.Semigroup`

`>>>`

[Arg () "dog"]`intersect [Arg () "dog"] [Arg () "cow", Arg () "cat"]`

However if the first list contains duplicates, so will the result.

`>>>`

"oo"`"coot" `intersect` "heron"`

`>>>`

"o"`"heron" `intersect` "coot"`

If the second list is infinite, `intersect`

either hangs
or returns its first argument in full. Otherwise if the first list
is infinite, `intersect`

might be productive:

`>>>`

[100,101,102,103...`intersect [100..] [0..]`

`>>>`

* Hangs forever *`intersect [0] [1..]`

`>>>`

* Hangs forever *`intersect [1..] [0]`

`>>>`

[2,2,2,2...`intersect (cycle [1..3]) [2]`

## Ordered lists

sort :: Ord a => [a] -> [a] Source #

The `sort`

function implements a stable sorting algorithm.
It is a special case of `sortBy`

, which allows the programmer to supply
their own comparison function.

Elements are arranged from lowest to highest, keeping duplicates in the order they appeared in the input.

The argument must be finite.

#### Examples

`>>>`

[1,2,3,4,5,6]`sort [1,6,4,3,2,5]`

`>>>`

"aehklls"`sort "haskell"`

`>>>`

`import Data.Semigroup(Arg(..))`

`>>>`

[Arg ":)" 0,Arg ":)" 1,Arg ":3" 0,Arg ":D" 0,Arg ":D" 1]`sort [Arg ":)" 0, Arg ":D" 0, Arg ":)" 1, Arg ":3" 0, Arg ":D" 1]`

sortOn :: Ord b => (a -> b) -> [a] -> [a] Source #

Sort a list by comparing the results of a key function applied to each
element.

is equivalent to `sortOn`

f

, but has the
performance advantage of only evaluating `sortBy`

(`comparing`

f)`f`

once for each element in the
input list. This is called the decorate-sort-undecorate paradigm, or
Schwartzian transform.

Elements are arranged from lowest to highest, keeping duplicates in the order they appeared in the input.

The argument must be finite.

#### Examples

`>>>`

[(1,"Hello"),(2,"world"),(4,"!")]`sortOn fst [(2, "world"), (4, "!"), (1, "Hello")]`

`>>>`

["jim","pam","creed","kevin","dwight","michael"]`sortOn length ["jim", "creed", "pam", "michael", "dwight", "kevin"]`

#### Performance notes

This function minimises the projections performed, by materialising the projections in an intermediate list.

For trivial projections, you should prefer using `sortBy`

with
`comparing`

, for example:

`>>>`

[(1,3),(2,2),(3,1)]`sortBy (comparing fst) [(3, 1), (2, 2), (1, 3)]`

Or, for the exact same API as `sortOn`

, you can use `sortBy . comparing`:

`>>>`

[(1,3),(2,2),(3,1)]`(sortBy . comparing) fst [(3, 1), (2, 2), (1, 3)]`

*Since: base-4.8.0.0*

insert :: Ord a => a -> [a] -> [a] Source #

\(\mathcal{O}(n)\). The `insert`

function takes an element and a list and
inserts the element into the list at the first position where it is less than
or equal to the next element. In particular, if the list is sorted before the
call, the result will also be sorted. It is a special case of `insertBy`

,
which allows the programmer to supply their own comparison function.

#### Examples

`>>>`

[-1,1,2,3]`insert (-1) [1, 2, 3]`

`>>>`

"abcdefg"`insert 'd' "abcefg"`

`>>>`

[1,2,3,4,5,6,7]`insert 4 [1, 2, 3, 5, 6, 7]`

# Generalized functions

## The "`By`

" operations

By convention, overloaded functions have a non-overloaded
counterpart whose name is suffixed with ``By`

'.

It is often convenient to use these functions together with
`on`

, for instance

.`sortBy`

(`compare`

`on` `fst`

)

### User-supplied equality (replacing an `Eq`

context)

The predicate is assumed to define an equivalence.

nubBy :: (a -> a -> Bool) -> [a] -> [a] Source #

The `nubBy`

function behaves just like `nub`

, except it uses a
user-supplied equality predicate instead of the overloaded `(==)`

function.

#### Examples

`>>>`

[1,2,6]`nubBy (\x y -> mod x 3 == mod y 3) [1,2,4,5,6]`

`>>>`

[2,2,2]`nubBy (/=) [2, 7, 1, 8, 2, 8, 1, 8, 2, 8]`

`>>>`

[1,2,3,5,5]`nubBy (>) [1, 2, 3, 2, 1, 5, 4, 5, 3, 2]`

deleteFirstsBy :: (a -> a -> Bool) -> [a] -> [a] -> [a] Source #

The `deleteFirstsBy`

function takes a predicate and two lists and
returns the first list with the first occurrence of each element of
the second list removed. This is the non-overloaded version of `(\\)`

.

(\\) == deleteFirstsBy (==)

The second list must be finite, but the first may be infinite.

#### Examples

`>>>`

[4,5,6,7,8,9,10]`deleteFirstsBy (>) [1..10] [3, 4, 5]`

`>>>`

[4,5,6,7,8,9,10]`deleteFirstsBy (/=) [1..10] [1, 3, 5]`

intersectBy :: (a -> a -> Bool) -> [a] -> [a] -> [a] Source #

The `intersectBy`

function is the non-overloaded version of `intersect`

.
It is productive for infinite arguments only if the first one
is a subset of the second.

groupBy :: (a -> a -> Bool) -> [a] -> [[a]] Source #

The `groupBy`

function is the non-overloaded version of `group`

.

When a supplied relation is not transitive, it is important to remember that equality is checked against the first element in the group, not against the nearest neighbour:

`>>>`

[[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14],[15,16,17,18,19]]`groupBy (\a b -> b - a < 5) [0..19]`

It's often preferable to use `Data.List.NonEmpty.`

`groupBy`

,
which provides type-level guarantees of non-emptiness of inner lists.

#### Examples

`>>>`

[[1],[1],[1,2,3],[1,4,4,5]]`groupBy (/=) [1, 1, 1, 2, 3, 1, 4, 4, 5]`

`>>>`

[[1],[3],[5,1,4,2],[6,5,4]]`groupBy (>) [1, 3, 5, 1, 4, 2, 6, 5, 4]`

`>>>`

[[True,False],[True,False,False,False],[True]]`groupBy (const not) [True, False, True, False, False, False, True]`

### User-supplied comparison (replacing an `Ord`

context)

The function is assumed to define a total ordering.

sortBy :: (a -> a -> Ordering) -> [a] -> [a] Source #

The `sortBy`

function is the non-overloaded version of `sort`

.
The argument must be finite.

The supplied comparison relation is supposed to be reflexive and antisymmetric,
otherwise, e. g., for `_ _ -> GT`

, the ordered list simply does not exist.
The relation is also expected to be transitive: if it is not then `sortBy`

might fail to find an ordered permutation, even if it exists.

#### Examples

`>>>`

[(1,"Hello"),(2,"world"),(4,"!")]`sortBy (\(a,_) (b,_) -> compare a b) [(2, "world"), (4, "!"), (1, "Hello")]`

insertBy :: (a -> a -> Ordering) -> a -> [a] -> [a] Source #

\(\mathcal{O}(n)\). The non-overloaded version of `insert`

.

#### Examples

`>>>`

[[1],[1,2],[1,2,3],[1,2,3,4]]`insertBy (\x y -> compare (length x) (length y)) [1, 2] [[1], [1, 2, 3], [1, 2, 3, 4]]`

maximumBy :: (a -> a -> Ordering) -> [a] -> a Source #

The `maximumBy`

function is the non-overloaded version of `maximum`

,
which takes a comparison function and a list
and returns the greatest element of the list by the comparison function.
The list must be finite and non-empty.

#### Examples

We can use this to find the longest entry of a list:

`>>>`

"Longest"`maximumBy (\x y -> compare (length x) (length y)) ["Hello", "World", "!", "Longest", "bar"]`

`>>>`

(10, 15)`minimumBy (\(a, b) (c, d) -> compare (abs (a - b)) (abs (c - d))) [(10, 15), (1, 2), (3, 5)]`

minimumBy :: (a -> a -> Ordering) -> [a] -> a Source #

The `minimumBy`

function is the non-overloaded version of `minimum`

,
which takes a comparison function and a list
and returns the least element of the list by the comparison function.
The list must be finite and non-empty.

#### Examples

We can use this to find the shortest entry of a list:

`>>>`

"!"`minimumBy (\x y -> compare (length x) (length y)) ["Hello", "World", "!", "Longest", "bar"]`

`>>>`

(1, 2)`minimumBy (\(a, b) (c, d) -> compare (abs (a - b)) (abs (c - d))) [(10, 15), (1, 2), (3, 5)]`

## The "`generic`

" operations

The prefix ``generic`

' indicates an overloaded function that
is a generalized version of a Prelude function.

genericLength :: Num i => [a] -> i Source #

\(\mathcal{O}(n)\). The `genericLength`

function is an overloaded version
of `length`

. In particular, instead of returning an `Int`

, it returns any
type which is an instance of `Num`

. It is, however, less efficient than
`length`

.

#### Examples

`>>>`

3`genericLength [1, 2, 3] :: Int`

`>>>`

3.0`genericLength [1, 2, 3] :: Float`

Users should take care to pick a return type that is wide enough to contain
the full length of the list. If the width is insufficient, the overflow
behaviour will depend on the `(+)`

implementation in the selected `Num`

instance. The following example overflows because the actual list length
of 200 lies outside of the `Int8`

range of `-128..127`

.

`>>>`

-56`genericLength [1..200] :: Int8`

genericTake :: Integral i => i -> [a] -> [a] Source #

The `genericTake`

function is an overloaded version of `take`

, which
accepts any `Integral`

value as the number of elements to take.

genericDrop :: Integral i => i -> [a] -> [a] Source #

The `genericDrop`

function is an overloaded version of `drop`

, which
accepts any `Integral`

value as the number of elements to drop.

genericSplitAt :: Integral i => i -> [a] -> ([a], [a]) Source #

The `genericSplitAt`

function is an overloaded version of `splitAt`

, which
accepts any `Integral`

value as the position at which to split.

genericIndex :: Integral i => [a] -> i -> a Source #

The `genericIndex`

function is an overloaded version of `!!`

, which
accepts any `Integral`

value as the index.

genericReplicate :: Integral i => i -> a -> [a] Source #

The `genericReplicate`

function is an overloaded version of `replicate`

,
which accepts any `Integral`

value as the number of repetitions to make.