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 :: [a] -> a
- last :: [a] -> a
- tail :: [a] -> [a]
- init :: [a] -> [a]
- uncons :: [a] -> Maybe (a, [a])
- singleton :: a -> [a]
- null :: Foldable t => t a -> Bool
- length :: Foldable t => t 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 :: Foldable t => (b -> a -> b) -> b -> t a -> b
- foldl' :: Foldable t => (b -> a -> b) -> b -> t a -> b
- foldl1 :: Foldable t => (a -> a -> a) -> t a -> a
- foldl1' :: (a -> a -> a) -> [a] -> a
- foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b
- foldr1 :: Foldable t => (a -> a -> a) -> t a -> a
- concat :: Foldable t => t [a] -> [a]
- concatMap :: Foldable t => (a -> [b]) -> t a -> [b]
- and :: Foldable t => t Bool -> Bool
- or :: Foldable t => t Bool -> Bool
- any :: Foldable t => (a -> Bool) -> t a -> Bool
- all :: Foldable t => (a -> Bool) -> t a -> Bool
- sum :: (Foldable t, Num a) => t a -> a
- product :: (Foldable t, Num a) => t a -> a
- maximum :: forall a. (Foldable t, Ord a) => t a -> a
- minimum :: forall a. (Foldable t, Ord a) => t 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 :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)
- mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)
- iterate :: (a -> a) -> a -> [a]
- iterate' :: (a -> a) -> a -> [a]
- repeat :: a -> [a]
- replicate :: Int -> a -> [a]
- cycle :: [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
- isSubsequenceOf :: Eq a => [a] -> [a] -> Bool
- elem :: (Foldable t, Eq a) => a -> t a -> Bool
- notElem :: (Foldable t, Eq a) => a -> t a -> Bool
- lookup :: Eq a => a -> [(a, b)] -> Maybe b
- find :: Foldable t => (a -> Bool) -> t a -> Maybe a
- filter :: (a -> Bool) -> [a] -> [a]
- partition :: (a -> Bool) -> [a] -> ([a], [a])
- (!!) :: [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 :: Foldable t => (a -> a -> Ordering) -> t a -> a
- minimumBy :: Foldable t => (a -> a -> Ordering) -> t 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 #

Append 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.

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

`>>>`

1`head [1, 2, 3]`

`>>>`

1`head [1..]`

`>>>`

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

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

`>>>`

3`last [1, 2, 3]`

`>>>`

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

`>>>`

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

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

`>>>`

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

`>>>`

[]`tail [1]`

`>>>`

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

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

`>>>`

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

`>>>`

[]`init [1]`

`>>>`

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

null :: Foldable t => t a -> Bool Source #

Test whether the structure is empty. The default implementation is Left-associative and lazy in both the initial element and the accumulator. Thus optimised for structures where the first element can be accessed in constant time. Structures where this is not the case should have a non-default implementation.

#### Examples

Basic usage:

`>>>`

True`null []`

`>>>`

False`null [1]`

`null`

is expected to terminate even for infinite structures.
The default implementation terminates provided the structure
is bounded on the left (there is a left-most element).

`>>>`

False`null [1..]`

*Since: base-4.8.0.0*

length :: Foldable t => t a -> Int Source #

Returns the size/length of a finite structure as an `Int`

. The
default implementation just counts elements starting with the left-most.
Instances for structures that can compute the element count faster
than via element-by-element counting, should provide a specialised
implementation.

#### Examples

Basic usage:

`>>>`

0`length []`

`>>>`

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

`>>>`

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

*Since: base-4.8.0.0*

# 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, ...]

`>>>`

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

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

`reverse`

`xs`

returns the elements of `xs`

in reverse order.
`xs`

must be finite.

`>>>`

[]`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. For
example,

`>>>`

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

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.

`>>>`

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

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

The `transpose`

function transposes the rows and columns of its argument.
For example,

`>>>`

[[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]]`

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

The `subsequences`

function returns the list of all subsequences of the argument.

`>>>`

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

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

The `permutations`

function returns the list of all permutations of the argument.

`>>>`

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

# Reducing lists (folds)

foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b Source #

Left-associative fold of a structure, lazy in the accumulator. This is rarely what you want, but can work well for structures with efficient right-to-left sequencing and an operator that is lazy in its left argument.

In the case of lists, `foldl`

, when 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

Note that to produce the outermost application of the operator the
entire input list must be traversed. Like all left-associative folds,
`foldl`

will diverge if given an infinite list.

If you want an efficient strict left-fold, you probably want to use
`foldl`

` instead of `foldl`

. The reason for this is that the latter
does not force the *inner* results (e.g. `z `f` x1`

in the above
example) before applying them to the operator (e.g. to `(`f` x2)`

).
This results in a thunk chain \(\mathcal{O}(n)\) elements long, which
then must be evaluated from the outside-in.

For a general `Foldable`

structure this should be semantically identical
to:

foldl f z =`foldl`

f z .`toList`

#### Examples

The first example is a strict fold, which in practice is best performed
with `foldl`

`.

`>>>`

52`foldl (+) 42 [1,2,3,4]`

Though the result below is lazy, the input is reversed before prepending it to the initial accumulator, so corecursion begins only after traversing the entire input string.

`>>>`

"hgfeabcd"`foldl (\acc c -> c : acc) "abcd" "efgh"`

A left fold of a structure that is infinite on the right cannot terminate, even when for any finite input the fold just returns the initial accumulator:

`>>>`

* Hangs forever *`foldl (\a _ -> a) 0 $ repeat 1`

foldl' :: Foldable t => (b -> a -> b) -> b -> t a -> b Source #

Left-associative fold of a structure but with strict application of the operator.

This ensures that each step of the fold is forced to Weak Head Normal
Form before being applied, avoiding the collection of thunks that would
otherwise occur. This is often what you want to strictly reduce a
finite structure to a single strict result (e.g. `sum`

).

For a general `Foldable`

structure this should be semantically identical
to,

foldl' f z =`foldl'`

f z .`toList`

*Since: base-4.6.0.0*

foldl1 :: Foldable t => (a -> a -> a) -> t a -> a Source #

A variant of `foldl`

that has no base case,
and thus may only be applied to non-empty structures.

This function is non-total and will raise a runtime exception if the structure happens to be empty.

`foldl1`

f =`foldl1`

f .`toList`

#### Examples

Basic usage:

`>>>`

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

`>>>`

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

`>>>`

*** Exception: foldl1: empty structure`foldl1 (+) Nothing`

`>>>`

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

`>>>`

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

`>>>`

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

`>>>`

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

foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b Source #

Right-associative fold of a structure, lazy in the accumulator.

In the case of lists, `foldr`

, when 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)...)

Note that since the head of the resulting expression is produced by an
application of the operator to the first element of the list, given an
operator lazy in its right argument, `foldr`

can produce a terminating
expression from an unbounded list.

For a general `Foldable`

structure this should be semantically identical
to,

foldr f z =`foldr`

f z .`toList`

#### Examples

Basic usage:

`>>>`

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

`>>>`

False`foldr (||) False []`

`>>>`

"foodcba"`foldr (\c acc -> acc ++ [c]) "foo" ['a', 'b', 'c', 'd']`

##### Infinite structures

⚠️ Applying `foldr`

to infinite structures usually doesn't terminate.

It may still terminate under one of the following conditions:

- the folding function is short-circuiting
- the folding function is lazy on its second argument

###### Short-circuiting

`(`

short-circuits on `||`

)`True`

values, so the following terminates
because there is a `True`

value finitely far from the left side:

`>>>`

True`foldr (||) False (True : repeat False)`

But the following doesn't terminate:

`>>>`

* Hangs forever *`foldr (||) False (repeat False ++ [True])`

###### Laziness in the second argument

Applying `foldr`

to infinite structures terminates when the operator is
lazy in its second argument (the initial accumulator is never used in
this case, and so could be left `undefined`

, but `[]`

is more clear):

`>>>`

[1,4,7,10,13]`take 5 $ foldr (\i acc -> i : fmap (+3) acc) [] (repeat 1)`

foldr1 :: Foldable t => (a -> a -> a) -> t a -> a Source #

A variant of `foldr`

that has no base case,
and thus may only be applied to non-empty structures.

This function is non-total and will raise a runtime exception if the structure happens to be empty.

#### Examples

Basic usage:

`>>>`

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

`>>>`

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

`>>>`

*** Exception: foldr1: empty structure`foldr1 (+) Nothing`

`>>>`

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

`>>>`

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

`>>>`

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

`>>>`

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

## Special folds

concat :: Foldable t => t [a] -> [a] Source #

The concatenation of all the elements of a container of lists.

#### Examples

Basic usage:

`>>>`

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

`>>>`

[]`concat (Left 42)`

`>>>`

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

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

Map a function over all the elements of a container and concatenate the resulting lists.

#### Examples

Basic usage:

`>>>`

[1,2,3,10,11,12,100,101,102,1000,1001,1002]`concatMap (take 3) [[1..], [10..], [100..], [1000..]]`

`>>>`

[1,2,3]`concatMap (take 3) (Just [1..])`

and :: Foldable t => t Bool -> Bool Source #

`and`

returns the conjunction of a container of Bools. For the
result to be `True`

, the container must be finite; `False`

, however,
results from a `False`

value finitely far from the left end.

#### Examples

Basic usage:

`>>>`

True`and []`

`>>>`

True`and [True]`

`>>>`

False`and [False]`

`>>>`

False`and [True, True, False]`

`>>>`

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

`>>>`

* Hangs forever *`and (repeat True)`

or :: Foldable t => t Bool -> Bool Source #

`or`

returns the disjunction of a container of Bools. For the
result to be `False`

, the container must be finite; `True`

, however,
results from a `True`

value finitely far from the left end.

#### Examples

Basic usage:

`>>>`

False`or []`

`>>>`

True`or [True]`

`>>>`

False`or [False]`

`>>>`

True`or [True, True, False]`

`>>>`

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

`>>>`

* Hangs forever *`or (repeat False)`

any :: Foldable t => (a -> Bool) -> t a -> Bool Source #

Determines whether any element of the structure satisfies the predicate.

#### Examples

Basic usage:

`>>>`

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 :: Foldable t => (a -> Bool) -> t a -> Bool Source #

Determines whether all elements of the structure satisfy the predicate.

#### Examples

Basic usage:

`>>>`

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 :: (Foldable t, Num a) => t a -> a Source #

The `sum`

function computes the sum of the numbers of a structure.

#### Examples

Basic usage:

`>>>`

0`sum []`

`>>>`

42`sum [42]`

`>>>`

55`sum [1..10]`

`>>>`

7.8`sum [4.1, 2.0, 1.7]`

`>>>`

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

*Since: base-4.8.0.0*

product :: (Foldable t, Num a) => t a -> a Source #

The `product`

function computes the product of the numbers of a
structure.

#### Examples

Basic usage:

`>>>`

1`product []`

`>>>`

42`product [42]`

`>>>`

3628800`product [1..10]`

`>>>`

13.939999999999998`product [4.1, 2.0, 1.7]`

`>>>`

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

*Since: base-4.8.0.0*

maximum :: forall a. (Foldable t, Ord a) => t a -> a Source #

The largest element of a non-empty structure.

This function is non-total and will raise a runtime exception if the structure happens to be empty. A structure that supports random access and maintains its elements in order should provide a specialised implementation to return the maximum in faster than linear time.

#### Examples

Basic usage:

`>>>`

10`maximum [1..10]`

`>>>`

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

`>>>`

*** Exception: maximum: empty structure`maximum Nothing`

*Since: base-4.8.0.0*

minimum :: forall a. (Foldable t, Ord a) => t a -> a Source #

The least element of a non-empty structure.

This function is non-total and will raise a runtime exception if the structure happens to be empty A structure that supports random access and maintains its elements in order should provide a specialised implementation to return the minimum in faster than linear time.

#### Examples

Basic usage:

`>>>`

1`minimum [1..10]`

`>>>`

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

`>>>`

*** Exception: minimum: empty structure`minimum Nothing`

*Since: base-4.8.0.0*

# 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

`>>>`

[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']`

`>>>`

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

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, ...]

`>>>`

[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]`

`>>>`

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

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.

`>>>`

[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']`

`>>>`

* Hangs forever *`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.

`>>>`

[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]`

`>>>`

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

## Accumulating maps

mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) Source #

The `mapAccumL`

function behaves like a combination of `fmap`

and `foldl`

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

#### Examples

Basic usage:

`>>>`

(55,[0,1,3,6,10,15,21,28,36,45])`mapAccumL (\a b -> (a + b, a)) 0 [1..10]`

`>>>`

("012345",["0","01","012","0123","01234"])`mapAccumL (\a b -> (a <> show b, a)) "0" [1..5]`

mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) Source #

The `mapAccumR`

function behaves like a combination of `fmap`

and `foldr`

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

#### Examples

Basic usage:

`>>>`

(55,[54,52,49,45,40,34,27,19,10,0])`mapAccumR (\a b -> (a + b, a)) 0 [1..10]`

`>>>`

("054321",["05432","0543","054","05","0"])`mapAccumR (\a b -> (a <> show b, a)) "0" [1..5]`

## 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), ...]

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.

`>>>`

[True,False,True,False...`iterate not True`

`>>>`

[42,45,48,51,54,57,60,63...`iterate (+3) 42`

`repeat`

`x`

is an infinite list, with `x`

the value of every element.

`>>>`

[17,17,17,17,17,17,17,17,17...`repeat 17`

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.

`>>>`

[]`replicate 0 True`

`>>>`

[]`replicate (-1) True`

`>>>`

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

`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.

`>>>`

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

`>>>`

[42,42,42,42,42,42,42,42,42,42...`cycle [42]`

`>>>`

[2,5,7,2,5,7,2,5,7,2,5,7...`cycle [2, 5, 7]`

## 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

A simple use of unfoldr:

`>>>`

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

# 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

`>>>`

"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]`

It is an instance of the more general `genericTake`

,
in which `n`

may be of any integral type.

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

`drop`

`n xs`

returns the suffix of `xs`

after the first `n`

elements, or `[]`

if `n > `

.`length`

xs

`>>>`

"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]`

It is an instance of the more general `genericDrop`

,
in which `n`

may be of any integral type.

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:

`>>>`

("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]`

It is equivalent to `(`

when `take`

n xs, `drop`

n xs)`n`

is not `_|_`

(`splitAt _|_ xs = _|_`

).
`splitAt`

is an instance of the more general `genericSplitAt`

,
in which `n`

may be of any integral type.

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`

.

`>>>`

[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. For example:

`>>>`

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

`>>>`

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

dropWhileEnd isSpace ("foo\n" ++ undefined) == "foo" ++ undefined

*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 longest prefix (possibly empty) of `xs`

of elements that
satisfy `p`

and second element is the remainder of the list:

`>>>`

([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:

`>>>`

([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.

`>>>`

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 contains only equal elements. For example,

`>>>`

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

It is a special case of `groupBy`

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

## 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.

`>>>`

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

`>>>`

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

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. The second list must be
finite.

`>>>`

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

`>>>`

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

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

The `isSubsequenceOf`

function takes two lists and returns `True`

if all
the elements of the first list occur, in order, in the second. The
elements do not have to occur consecutively.

is equivalent to `isSubsequenceOf`

x y

.`elem`

x (`subsequences`

y)

#### Examples

`>>>`

True`isSubsequenceOf "GHC" "The Glorious Haskell Compiler"`

`>>>`

True`isSubsequenceOf ['a','d'..'z'] ['a'..'z']`

`>>>`

False`isSubsequenceOf [1..10] [10,9..0]`

*Since: base-4.8.0.0*

# Searching lists

## Searching by equality

elem :: (Foldable t, Eq a) => a -> t a -> Bool infix 4 Source #

Does the element occur in the structure?

Note: `elem`

is often used in infix form.

#### Examples

Basic usage:

`>>>`

False`3 `elem` []`

`>>>`

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

`>>>`

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

For infinite structures, the default implementation of `elem`

terminates if the sought-after value exists at a finite distance
from the left side of the structure:

`>>>`

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

`>>>`

* Hangs forever *`3 `elem` ([4..] ++ [3])`

*Since: base-4.8.0.0*

notElem :: (Foldable t, Eq a) => a -> t a -> Bool infix 4 Source #

`notElem`

is the negation of `elem`

.

#### Examples

Basic usage:

`>>>`

True`3 `notElem` []`

`>>>`

True`3 `notElem` [1,2]`

`>>>`

False`3 `notElem` [1,2,3,4,5]`

For infinite structures, `notElem`

terminates if the value exists at a
finite distance from the left side of the structure:

`>>>`

False`3 `notElem` [1..]`

`>>>`

* Hangs forever *`3 `notElem` ([4..] ++ [3])`

lookup :: Eq a => a -> [(a, b)] -> Maybe b Source #

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

`key assocs`

looks up a key in an association
list.

`>>>`

Nothing`lookup 2 []`

`>>>`

Nothing`lookup 2 [(1, "first")]`

`>>>`

Just "second"`lookup 2 [(1, "first"), (2, "second"), (3, "third")]`

## Searching with a predicate

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]

`>>>`

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

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

The `partition`

function takes a predicate 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)

`>>>`

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

# Indexing lists

These functions treat a list `xs`

as a indexed collection,
with indices ranging from 0 to

.`length`

xs - 1

(!!) :: [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.

`>>>`

'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)`

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.

`>>>`

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

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

The `findIndices`

function extends `findIndex`

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

`>>>`

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

# 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.

`>>>`

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

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..] []`

`zip`

is right-lazy:

`>>>`

[]`zip [] _|_`

`>>>`

_|_`zip _|_ []`

`zip`

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

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..]

For example,

is applied to two lists to produce the list of
corresponding sums:`zipWith`

(+)

`>>>`

[5,7,9]`zipWith (+) [1, 2, 3] [4, 5, 6]`

`zipWith`

is right-lazy:

`>>>`

[]`zipWith f [] _|_`

`zipWith`

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

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

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..]

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.

`>>>`

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

`>>>`

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

# Special lists

## Functions on strings

lines :: String -> [String] Source #

`lines`

breaks a string up into a list of strings at newline
characters. The resulting strings do not contain newlines.

Note that after splitting the string at newline characters, the last part of the string is considered a line even if it doesn't end with a newline. For example,

`>>>`

[]`lines ""`

`>>>`

[""]`lines "\n"`

`>>>`

["one"]`lines "one"`

`>>>`

["one"]`lines "one\n"`

`>>>`

["one",""]`lines "one\n\n"`

`>>>`

["one","two"]`lines "one\ntwo"`

`>>>`

["one","two"]`lines "one\ntwo\n"`

Thus

contains at least as many elements as newlines in `lines`

s`s`

.

words :: String -> [String] Source #

`words`

breaks a string up into a list of words, which were delimited
by white space.

`>>>`

["Lorem","ipsum","dolor"]`words "Lorem ipsum\ndolor"`

## "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.

`>>>`

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

(\\) :: 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.

`>>>`

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

It is a special case of `deleteFirstsBy`

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

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

The `union`

function returns the list union of the two lists.
For example,

`>>>`

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

Duplicates, and elements of the first list, are removed from the
the second list, but if the first list contains duplicates, so will
the result.
It is a special case of `unionBy`

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

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

The `intersect`

function takes the list intersection of two lists.
For example,

`>>>`

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

If the first list contains duplicates, so will the result.

`>>>`

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

It is a special case of `intersectBy`

, which allows the programmer to
supply their own equality test. If the element is found in both the first
and the second list, the element from the first list will be used.

## Ordered lists

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

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

is equivalent to `sortBy (comparing f)`

, but has the
performance advantage of only evaluating `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.

`>>>`

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

*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.

`>>>`

[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.

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.

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

The `intersectBy`

function is the non-overloaded version of `intersect`

.

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

context)

The function is assumed to define a total ordering.

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

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

.

maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a Source #

The largest element of a non-empty structure with respect to the given comparison function.

#### Examples

Basic usage:

`>>>`

"Longest"`maximumBy (compare `on` length) ["Hello", "World", "!", "Longest", "bar"]`

minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a Source #

The least element of a non-empty structure with respect to the given comparison function.

#### Examples

Basic usage:

`>>>`

"!"`minimumBy (compare `on` length) ["Hello", "World", "!", "Longest", "bar"]`

## 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`

.

`>>>`

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

`>>>`

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

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.