HORIZON HASKELLDocslts/ghc-9.10.x248f8f02026-10-05Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · 248f8f0 · 2026-10-05

Moduleextra-1.8Haskell2010

Data.List.Extra

This module extends Data.List with extra functions of a similar nature. The package also exports the existing Data.List functions. Some of the names and semantics were inspired by the text package.

  • 1 type
  • 186 values
  • Packageextra-1.8
  • Exports199
  • LanguageHaskell2010
  • LicenceBSD-3-Clause
  • SourceExtra.hs
valuegroup :: Eq a => [a] -> [[a]]
#

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
Example1 expression
group "Mississippi"["M","i","ss","i","ss","i","pp","i"]
Example1 expression
group [1, 1, 1, 2, 2, 3, 4, 5, 5][[1,1,1],[2,2],[3],[4],[5,5]]
value(!?) :: [a] -> Int -> Maybe a
#

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
Example1 expression
['a', 'b', 'c'] !? 0Just 'a'
Example1 expression
['a', 'b', 'c'] !? 2Just 'c'
Example1 expression
['a', 'b', 'c'] !? 3Nothing
Example1 expression
['a', 'b', 'c'] !? (-1)Nothing
valueunsnoc :: [a] -> Maybe ([a], a)
#

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

  • If the list is empty, returns Nothing.

  • If the list is non-empty, returns Just (xs, x), where xs is the initial 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
Example1 expression
unsnoc []Nothing
Example1 expression
unsnoc [1]Just ([],1)
Example1 expression
unsnoc [1, 2, 3]Just ([1,2],3)
Laziness
Example1 expression
fst <$> unsnoc [undefined]Just []
Example1 expression
head . fst <$> unsnoc (1 : undefined)Just *** Exception: Prelude.undefined
Example1 expression
head . fst <$> unsnoc (1 : 2 : undefined)Just 1
valuesortOn :: Ord b => (a -> b) -> [a] -> [a]
#

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.

The argument must be finite.

Examples
Example1 expression
sortOn fst [(2, "world"), (4, "!"), (1, "Hello")][(1,"Hello"),(2,"world"),(4,"!")]
Example1 expression
sortOn length ["jim", "creed", "pam", "michael", "dwight", "kevin"]["jim","pam","creed","kevin","dwight","michael"]
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:

Example1 expression
sortBy (comparing fst) [(3, 1), (2, 2), (1, 3)][(1,3),(2,2),(3,1)]

Or, for the exact same API as sortOn, you can use `sortBy . comparing`:

Example1 expression
(sortBy . comparing) fst [(3, 1), (2, 2), (1, 3)][(1,3),(2,2),(3,1)]
valueunion :: Eq a => [a] -> [a] -> [a]
#

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
Example1 expression
"dog" `union` "cow""dogcw"

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:

Example3 expressions
import Data.Semigroup(Arg(..))union [Arg () "dog"] [Arg () "cow"][Arg () "dog"]union [] [Arg () "dog", Arg () "cow"][Arg () "dog"]

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

Example2 expressions
"coot" `union` "duck""cootduk""duck" `union` "coot""duckot"

union is productive even if both arguments are infinite.

Example1 expression
[0, 2 ..] `union` [1, 3 ..][0,2,4,6,8,10,12..
valueunionBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
#

The unionBy function is the non-overloaded version of union. Both arguments may be infinite.

Examples
Example1 expression
unionBy (>) [3, 4, 5] [1, 2, 3, 4, 5, 6][3,4,5,4,5,6]
Example2 expressions
import Data.Semigroup (Arg(..))unionBy (/=) [Arg () "Saul"] [Arg () "Kim"][Arg () "Saul", Arg () "Kim"]
datadata List a
#

The builtin linked list type.

In Haskell, lists are one of the most important data types as they are often used analogous to loops in imperative programming languages. These lists are singly linked, which makes them unsuited for operations that require \mathcal{O}(1) access. Instead, they are intended to be traversed.

You can use List a or [a] in type signatures:

length :: [a] -> Int

or

length :: List a -> Int

They are fully equivalent, and List a will be normalised to [a].

Usage

Lists are constructed recursively using the right-associative constructor operator (or cons) (:) :: a -> [a] -> [a], which prepends an element to a list, and the empty list [].

(1 : 2 : 3 : []) == (1 : (2 : (3 : []))) == [1, 2, 3]

Lists can also be constructed using list literals of the form [x_1, x_2, ..., x_n] which are syntactic sugar and, unless -XOverloadedLists is enabled, are translated into uses of (:) and []

String literals, like "I 💜 hs", are translated into Lists of characters, ['I', ' ', '💜', ' ', 'h', 's'].

Implementation

Internally and in memory, all the above are represented like this, with arrows being pointers to locations in memory.

╭───┬───┬──╮   ╭───┬───┬──╮   ╭───┬───┬──╮   ╭────╮
│(:)│   │ ─┼──>│(:)│   │ ─┼──>│(:)│   │ ─┼──>│ [] │
╰───┴─┼─┴──╯   ╰───┴─┼─┴──╯   ╰───┴─┼─┴──╯   ╰────╯
      v              v              v
      1              2              3
Examples
>>> ['H', 'a', 's', 'k', 'e', 'l', 'l']
"Haskell"
>>> 1 : [4, 1, 5, 9]
[1,4,1,5,9]
>>> [] : [] : []
[[],[]]
Instances37Monad, Functor, MonadFix, MonadFail, Applicative, Foldable, …
valueall :: Foldable t => (a -> Bool) -> t a -> Bool
#

Determines whether all elements of the structure satisfy the predicate.

Examples

Basic usage:

Example1 expression
all (> 3) []True
Example1 expression
all (> 3) [1,2]False
Example1 expression
all (> 3) [1,2,3,4,5]False
Example1 expression
all (> 3) [1..]False
Example1 expression
all (> 3) [4..]* Hangs forever *
valueand :: Foldable t => t Bool -> Bool
#

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:

Example1 expression
and []True
Example1 expression
and [True]True
Example1 expression
and [False]False
Example1 expression
and [True, True, False]False
Example1 expression
and (False : repeat True) -- Infinite list [False,True,True,True,...False
Example1 expression
and (repeat True)* Hangs forever *
valueany :: Foldable t => (a -> Bool) -> t a -> Bool
#

Determines whether any element of the structure satisfies the predicate.

Examples

Basic usage:

Example1 expression
any (> 3) []False
Example1 expression
any (> 3) [1,2]False
Example1 expression
any (> 3) [1,2,3,4,5]True
Example1 expression
any (> 3) [1..]True
Example1 expression
any (> 3) [0, -1..]* Hangs forever *
valueconcat :: Foldable t => t [a] -> [a]
#

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

Examples

Basic usage:

Example1 expression
concat (Just [1, 2, 3])[1,2,3]
Example1 expression
concat (Left 42)[]
Example1 expression
concat [[1, 2, 3], [4, 5], [6], []][1,2,3,4,5,6]
valueconcatMap :: Foldable t => (a -> [b]) -> t a -> [b]
#

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

Examples

Basic usage:

Example1 expression
concatMap (take 3) [[1..], [10..], [100..], [1000..]][1,2,3,10,11,12,100,101,102,1000,1001,1002]
Example1 expression
concatMap (take 3) (Just [1..])[1,2,3]
valuenotElem :: (Foldable t, Eq a) => a -> t a -> Bool
#

notElem is the negation of elem.

Examples

Basic usage:

Example1 expression
3 `notElem` []True
Example1 expression
3 `notElem` [1,2]True
Example1 expression
3 `notElem` [1,2,3,4,5]False

For infinite structures, notElem terminates if the value exists at a finite distance from the left side of the structure:

Example1 expression
3 `notElem` [1..]False
Example1 expression
3 `notElem` ([4..] ++ [3])* Hangs forever *
valueor :: Foldable t => t Bool -> Bool
#

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:

Example1 expression
or []False
Example1 expression
or [True]True
Example1 expression
or [False]False
Example1 expression
or [True, True, False]True
Example1 expression
or (True : repeat False) -- Infinite list [True,False,False,False,...True
Example1 expression
or (repeat False)* Hangs forever *
valuelines :: String -> [String]
#

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
Example1 expression
lines ""           -- empty input contains no lines[]
Example1 expression
lines "\n"         -- single empty line[""]
Example1 expression
lines "one"        -- single unterminated line["one"]
Example1 expression
lines "one\n"      -- single non-empty line["one"]
Example1 expression
lines "one\n\n"    -- second line is empty["one",""]
Example1 expression
lines "one\ntwo"   -- second line is unterminated["one","two"]
Example1 expression
lines "one\ntwo\n" -- two non-empty lines["one","two"]
valueunlines :: [String] -> String
#

Appends a \n character to each input string, then concatenates the results. Equivalent to foldMap (s -> s ++ "\n").

Examples
Example1 expression
unlines ["Hello", "World", "!"]"Hello\nWorld\n!\n"

Note that unlines . lines /= id when the input is not \n-terminated:

Example1 expression
unlines . lines $ "foo\nbar""foo\nbar\n"
valueunwords :: [String] -> String
#

unwords joins words with separating spaces (U+0020 SPACE).

unwords is neither left nor right inverse of words:

Example2 expressions
words (unwords [" "])[]unwords (words "foo\nbar")"foo bar"
Examples
Example1 expression
unwords ["Lorem", "ipsum", "dolor"]"Lorem ipsum dolor"
Example1 expression
unwords ["foo", "bar", "", "baz"]"foo bar  baz"
valuewords :: String -> [String]
#

words breaks a string up into a list of words, which were delimited by white space (as defined by isSpace). This function trims any white spaces at the beginning and at the end.

Examples
Example1 expression
words "Lorem ipsum\ndolor"["Lorem","ipsum","dolor"]
Example1 expression
words " foo bar "["foo","bar"]
value(!!) :: HasCallStack => [a] -> Int -> a
#

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
Example1 expression
['a', 'b', 'c'] !! 0'a'
Example1 expression
['a', 'b', 'c'] !! 2'c'
Example1 expression
['a', 'b', 'c'] !! 3*** Exception: Prelude.!!: index too large
Example1 expression
['a', 'b', 'c'] !! (-1)*** Exception: Prelude.!!: negative index
valuebreak :: (a -> Bool) -> [a] -> ([a], [a])
#

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 span (not . p) and consequently to (takeWhile (not . p) xs, dropWhile (not . p) xs), even if p is _|_.

Laziness
Example1 expression
break undefined []([],[])
Example1 expression
fst (break (const True) undefined)*** Exception: Prelude.undefined
Example1 expression
fst (break (const True) (undefined : undefined))[]
Example1 expression
take 1 (fst (break (const False) (1 : undefined)))[1]

break produces the first component of the tuple lazily:

Example1 expression
take 10 (fst (break (const False) [1..]))[1,2,3,4,5,6,7,8,9,10]
Examples
Example1 expression
break (> 3) [1,2,3,4,1,2,3,4]([1,2,3],[4,1,2,3,4])
Example1 expression
break (< 9) [1,2,3]([],[1,2,3])
Example1 expression
break (> 9) [1,2,3]([1,2,3],[])
valuecycle :: HasCallStack => [a] -> [a]
#

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
Example1 expression
cycle []*** Exception: Prelude.cycle: empty list
Example1 expression
take 10 (cycle [42])[42,42,42,42,42,42,42,42,42,42]
Example1 expression
take 10 (cycle [2, 5, 7])[2,5,7,2,5,7,2,5,7,2]
Example1 expression
take 1 (cycle (42 : undefined))[42]
valuedrop :: Int -> [a] -> [a]
#

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
Example1 expression
drop 6 "Hello World!""World!"
Example1 expression
drop 3 [1,2,3,4,5][4,5]
Example1 expression
drop 3 [1,2][]
Example1 expression
drop 3 [][]
Example1 expression
drop (-1) [1,2][1,2]
Example1 expression
drop 0 [1,2][1,2]
valuedropWhile :: (a -> Bool) -> [a] -> [a]
#

dropWhile p xs returns the suffix remaining after takeWhile p xs.

Examples
Example1 expression
dropWhile (< 3) [1,2,3,4,5,1,2,3][3,4,5,1,2,3]
Example1 expression
dropWhile (< 9) [1,2,3][]
Example1 expression
dropWhile (< 0) [1,2,3][1,2,3]
valuehead :: HasCallStack => [a] -> a
#

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
Example1 expression
head [1, 2, 3]1
Example1 expression
head [1..]1
Example1 expression
head []*** Exception: Prelude.head: empty list
valueinit :: HasCallStack => [a] -> [a]
#

\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
Example1 expression
init [1, 2, 3][1,2]
Example1 expression
init [1][]
Example1 expression
init []*** Exception: Prelude.init: empty list
valueiterate :: (a -> a) -> a -> [a]
#

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.

Example1 expression
take 1 $ iterate undefined 42[42]
Examples
Example1 expression
take 10 $ iterate not True[True,False,True,False,True,False,True,False,True,False]
Example1 expression
take 10 $ iterate (+3) 42[42,45,48,51,54,57,60,63,66,69]

iterate id == repeat:

Example1 expression
take 10 $ iterate id 1[1,1,1,1,1,1,1,1,1,1]
valuelast :: HasCallStack => [a] -> a
#

\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
Example1 expression
last [1, 2, 3]3
Example1 expression
last [1..]* Hangs forever *
Example1 expression
last []*** Exception: Prelude.last: empty list
valuelookup :: Eq a => a -> [(a, b)] -> Maybe b
#

\mathcal{O}(n). lookup key assocs looks up a key in an association list. For the result to be Nothing, the list must be finite.

Examples
Example1 expression
lookup 2 []Nothing
Example1 expression
lookup 2 [(1, "first")]Nothing
Example1 expression
lookup 2 [(1, "first"), (2, "second"), (3, "third")]Just "second"
valuerepeat :: a -> [a]
#

repeat x is an infinite list, with x the value of every element.

Examples
Example1 expression
take 10 $ repeat 17[17,17,17,17,17,17,17,17,17, 17]
Example1 expression
repeat undefined[*** Exception: Prelude.undefined
valuereplicate :: Int -> a -> [a]
#

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
Example1 expression
replicate 0 True[]
Example1 expression
replicate (-1) True[]
Example1 expression
replicate 4 True[True,True,True,True]
valuereverse :: [a] -> [a]
#

\mathcal{O}(n). reverse xs returns the elements of xs in reverse order. xs must be finite.

Laziness

reverse is lazy in its elements.

Example1 expression
head (reverse [undefined, 1])1
Example1 expression
reverse (1 : 2 : undefined)*** Exception: Prelude.undefined
Examples
Example1 expression
reverse [][]
Example1 expression
reverse [42][42]
Example1 expression
reverse [2,5,7][7,5,2]
Example1 expression
reverse [1..]* Hangs forever *
valuescanl :: (b -> a -> b) -> b -> [a] -> [b]
#

\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
Example1 expression
scanl (+) 0 [1..4][0,1,3,6,10]
Example1 expression
scanl (+) 42 [][42]
Example1 expression
scanl (-) 100 [1..4][100,99,97,94,90]
Example1 expression
scanl (\reversedString nextChar -> nextChar : reversedString) "foo" ['a', 'b', 'c', 'd']["foo","afoo","bafoo","cbafoo","dcbafoo"]
Example1 expression
take 10 (scanl (+) 0 [1..])[0,1,3,6,10,15,21,28,36,45]
Example1 expression
take 1 (scanl undefined 'a' undefined)"a"
valuescanl1 :: (a -> a -> a) -> [a] -> [a]
#

\mathcal{O}(n). scanl1 is a variant of scanl that has no starting value argument:

scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
Examples
Example1 expression
scanl1 (+) [1..4][1,3,6,10]
Example1 expression
scanl1 (+) [][]
Example1 expression
scanl1 (-) [1..4][1,-1,-4,-8]
Example1 expression
scanl1 (&&) [True, False, True, True][True,False,False,False]
Example1 expression
scanl1 (||) [False, False, True, True][False,False,True,True]
Example1 expression
take 10 (scanl1 (+) [1..])[1,3,6,10,15,21,28,36,45,55]
Example1 expression
take 1 (scanl1 undefined ('a' : undefined))"a"
valuescanr :: (a -> b -> b) -> b -> [a] -> [b]
#

\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
Example1 expression
scanr (+) 0 [1..4][10,9,7,4,0]
Example1 expression
scanr (+) 42 [][42]
Example1 expression
scanr (-) 100 [1..4][98,-97,99,-96,100]
Example1 expression
scanr (\nextChar reversedString -> nextChar : reversedString) "foo" ['a', 'b', 'c', 'd']["abcdfoo","bcdfoo","cdfoo","dfoo","foo"]
Example1 expression
force $ scanr (+) 0 [1..]*** Exception: stack overflow
valuescanr1 :: (a -> a -> a) -> [a] -> [a]
#

\mathcal{O}(n). scanr1 is a variant of scanr that has no starting value argument.

Examples
Example1 expression
scanr1 (+) [1..4][10,9,7,4]
Example1 expression
scanr1 (+) [][]
Example1 expression
scanr1 (-) [1..4][-2,3,-1,4]
Example1 expression
scanr1 (&&) [True, False, True, True][False,False,True,True]
Example1 expression
scanr1 (||) [True, True, False, False][True,True,False,False]
Example1 expression
force $ scanr1 (+) [1..]*** Exception: stack overflow
valuespan :: (a -> Bool) -> [a] -> ([a], [a])
#

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 (takeWhile p xs, dropWhile p xs), even if p is _|_.

Laziness
Example4 expressions
span undefined []([],[])fst (span (const False) undefined)*** Exception: Prelude.undefinedfst (span (const False) (undefined : undefined))[]take 1 (fst (span (const True) (1 : undefined)))[1]

span produces the first component of the tuple lazily:

Example1 expression
take 10 (fst (span (const True) [1..]))[1,2,3,4,5,6,7,8,9,10]
Examples
Example1 expression
span (< 3) [1,2,3,4,1,2,3,4]([1,2],[3,4,1,2,3,4])
Example1 expression
span (< 9) [1,2,3]([1,2,3],[])
Example1 expression
span (< 0) [1,2,3]([],[1,2,3])
valuesplitAt :: Int -> [a] -> ([a], [a])
#

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 (take n xs, drop n xs) unless n is _|_: splitAt _|_ xs = _|_, not (_|_, _|_)).

The first component of the tuple is produced lazily:

Example1 expression
fst (splitAt 0 undefined)[]
Example1 expression
take 1 (fst (splitAt 10 (1 : undefined)))[1]
Examples
Example1 expression
splitAt 6 "Hello World!"("Hello ","World!")
Example1 expression
splitAt 3 [1,2,3,4,5]([1,2,3],[4,5])
Example1 expression
splitAt 1 [1,2,3]([1],[2,3])
Example1 expression
splitAt 3 [1,2,3]([1,2,3],[])
Example1 expression
splitAt 4 [1,2,3]([1,2,3],[])
Example1 expression
splitAt 0 [1,2,3]([],[1,2,3])
Example1 expression
splitAt (-1) [1,2,3]([],[1,2,3])
valuetail :: HasCallStack => [a] -> [a]
#

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
Example1 expression
tail [1, 2, 3][2,3]
Example1 expression
tail [1][]
Example1 expression
tail []*** Exception: Prelude.tail: empty list
valuetake :: Int -> [a] -> [a]
#

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
Example2 expressions
take 0 undefined[]take 2 (1 : 2 : undefined)[1,2]
Examples
Example1 expression
take 5 "Hello World!""Hello"
Example1 expression
take 3 [1,2,3,4,5][1,2,3]
Example1 expression
take 3 [1,2][1,2]
Example1 expression
take 3 [][]
Example1 expression
take (-1) [1,2][]
Example1 expression
take 0 [1,2][]
valuetakeWhile :: (a -> Bool) -> [a] -> [a]
#

takeWhile, applied to a predicate p and a list xs, returns the longest prefix (possibly empty) of xs of elements that satisfy p.

Laziness
Example1 expression
takeWhile (const False) undefined*** Exception: Prelude.undefined
Example1 expression
takeWhile (const False) (undefined : undefined)[]
Example1 expression
take 1 (takeWhile (const True) (1 : undefined))[1]
Examples
Example1 expression
takeWhile (< 3) [1,2,3,4,1,2,3,4][1,2]
Example1 expression
takeWhile (< 9) [1,2,3][1,2,3]
Example1 expression
takeWhile (< 0) [1,2,3][]
valueunzip :: [(a, b)] -> ([a], [b])
#

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

Examples
Example1 expression
unzip []([],[])
Example1 expression
unzip [(1, 'a'), (2, 'b')]([1,2],"ab")
valueunzip3 :: [(a, b, c)] -> ([a], [b], [c])
#

The unzip3 function takes a list of triples and returns three lists of the respective components, analogous to unzip.

Examples
Example1 expression
unzip3 []([],[],[])
Example1 expression
unzip3 [(1, 'a', True), (2, 'b', False)]([1,2],"ab",[True,False])
valuezip3 :: [a] -> [b] -> [c] -> [(a, b, c)]
#

zip3 takes three lists and returns a list of triples, analogous to zip. It is capable of list fusion, but it is restricted to its first list argument and its resulting list.

valuezipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
#

\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:

Example2 expressions
let f = undefinedzipWith f [] undefined[]

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

Examples

zipWith (+) can be applied to two lists to produce the list of corresponding sums:

Example1 expression
zipWith (+) [1, 2, 3] [4, 5, 6][5,7,9]
Example1 expression
zipWith (++) ["hello ", "foo"] ["world!", "bar"]["hello world!","foobar"]
valuezipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
#

\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
Example1 expression
zipWith3 (\x y z -> [x, y, z]) "123" "abc" "xyz"["1ax","2by","3cz"]
Example1 expression
zipWith3 (\x y z -> (x * y) + z) [1, 2, 3] [4, 5, 6] [7, 8, 9][11,18,27]
methodelem :: Eq a => a -> t a -> Bool
#

Does the element occur in the structure?

Note: elem is often used in infix form.

Examples

Basic usage:

Example1 expression
3 `elem` []False
Example1 expression
3 `elem` [1,2]False
Example1 expression
3 `elem` [1,2,3,4,5]True

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:

Example1 expression
3 `elem` [1..]True
Example1 expression
3 `elem` ([4..] ++ [3])* Hangs forever *
methodfoldl :: (b -> a -> b) -> b -> t a -> b
#

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

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

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.

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

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:

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

WARNING: When it comes to lists, you always want to use either foldl' or foldr instead.

methodfoldl' :: (b -> a -> b) -> b -> t a -> b
#

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
methodfoldl1 :: (a -> a -> a) -> t a -> a
#

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:

Example1 expression
foldl1 (+) [1..4]10
Example1 expression
foldl1 (+) []*** Exception: Prelude.foldl1: empty list
Example1 expression
foldl1 (+) Nothing*** Exception: foldl1: empty structure
Example1 expression
foldl1 (-) [1..4]-8
Example1 expression
foldl1 (&&) [True, False, True, True]False
Example1 expression
foldl1 (||) [False, False, True, True]True
Example1 expression
foldl1 (+) [1..]* Hangs forever *
methodfoldr :: (a -> b -> b) -> b -> t a -> b
#

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:

Example1 expression
foldr (||) False [False, True, False]True
Example1 expression
foldr (||) False []False
Example1 expression
foldr (\c acc -> acc ++ [c]) "foo" ['a', 'b', 'c', 'd']"foodcba"
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:

Example1 expression
foldr (||) False (True : repeat False)True

But the following doesn't terminate:

Example1 expression
foldr (||) False (repeat False ++ [True])* Hangs forever *
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):

Example1 expression
take 5 $ foldr (\i acc -> i : fmap (+3) acc) [] (repeat 1)[1,4,7,10,13]
methodfoldr1 :: (a -> a -> a) -> t a -> a
#

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:

Example1 expression
foldr1 (+) [1..4]10
Example1 expression
foldr1 (+) []Exception: Prelude.foldr1: empty list
Example1 expression
foldr1 (+) Nothing*** Exception: foldr1: empty structure
Example1 expression
foldr1 (-) [1..4]-2
Example1 expression
foldr1 (&&) [True, False, True, True]False
Example1 expression
foldr1 (||) [False, False, True, True]True
Example1 expression
foldr1 (+) [1..]* Hangs forever *
methodlength :: t a -> Int
#

Returns the size/length of a finite structure as an Int. The default implementation just counts elements starting with the leftmost. Instances for structures that can compute the element count faster than via element-by-element counting, should provide a specialised implementation.

Examples

Basic usage:

Example1 expression
length []0
Example2 expressions
length ['a', 'b', 'c']3length [1..]* Hangs forever *
methodmaximum :: Ord a => t a -> a
#

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:

Example1 expression
maximum [1..10]10
Example1 expression
maximum []*** Exception: Prelude.maximum: empty list
Example1 expression
maximum Nothing*** Exception: maximum: empty structure

WARNING: This function is partial for possibly-empty structures like lists.

methodminimum :: Ord a => t a -> a
#

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:

Example1 expression
minimum [1..10]1
Example1 expression
minimum []*** Exception: Prelude.minimum: empty list
Example1 expression
minimum Nothing*** Exception: minimum: empty structure

WARNING: This function is partial for possibly-empty structures like lists.

methodnull :: t a -> Bool
#

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:

Example1 expression
null []True
Example1 expression
null [1]False

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

Example1 expression
null [1..]False
methodproduct :: Num a => t a -> a
#

The product function computes the product of the numbers of a structure.

Examples

Basic usage:

Example1 expression
product []1
Example1 expression
product [42]42
Example1 expression
product [1..10]3628800
Example1 expression
product [4.1, 2.0, 1.7]13.939999999999998
Example1 expression
product [1..]* Hangs forever *
methodsum :: Num a => t a -> a
#

The sum function computes the sum of the numbers of a structure.

Examples

Basic usage:

Example1 expression
sum []0
Example1 expression
sum [42]42
Example1 expression
sum [1..10]55
Example1 expression
sum [4.1, 2.0, 1.7]7.8
Example1 expression
sum [1..]* Hangs forever *
value(++) :: [a] -> [a] -> [a]
#

(++) 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 GHC.Internal.Data.List.concat = GHC.Internal.Data.List.foldr (++) [] has linear performance, while GHC.Internal.Data.List.foldl (++) [] is prone to quadratic slowdown

Examples
Example1 expression
[1, 2, 3] ++ [4, 5, 6][1,2,3,4,5,6]
Example1 expression
[] ++ [1, 2, 3][1,2,3]
Example1 expression
[3, 2, 1] ++ [][3,2,1]
valuemap :: (a -> b) -> [a] -> [b]
#

\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
Example1 expression
map (+1) [1, 2, 3][2,3,4]
Example1 expression
map id [1, 2, 3][1,2,3]
Example1 expression
map (\n -> 3 * n + 1) [1, 2, 3][4,7,10]
valuezip :: [a] -> [b] -> [(a, b)]
#

\mathcal{O}(\min(m,n)). zip takes two lists and returns a list of corresponding pairs.

zip is right-lazy:

Example2 expressions
zip [] undefined[]zip undefined []*** Exception: Prelude.undefined...

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

Examples
Example1 expression
zip [1, 2, 3] ['a', 'b', 'c'][(1,'a'),(2,'b'),(3,'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:

Example1 expression
zip [1] ['a', 'b'][(1,'a')]
Example1 expression
zip [1, 2] ['a'][(1,'a')]
Example1 expression
zip [] [1..][]
Example1 expression
zip [1..] [][]
valuefilter :: (a -> Bool) -> [a] -> [a]
#

\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
Example1 expression
filter odd [1, 2, 3][1,3]
Example1 expression
filter (\l -> length l > 3) ["Hello", ", ", "World", "!"]["Hello","World"]
Example1 expression
filter (/= 3) [1, 2, 3, 4, 3, 2, 1][1,2,4,2,1]
valueisSuffixOf :: Eq a => [a] -> [a] -> Bool
#

The isSuffixOf function takes two lists and returns True iff the first list is a suffix of the second.

Examples
Example1 expression
"ld!" `isSuffixOf` "Hello World!"True
Example1 expression
"World" `isSuffixOf` "Hello World!"False

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

Example1 expression
[0..] `isSuffixOf` [0..99]False
Example1 expression
[0..99] `isSuffixOf` [0..]* Hangs forever *
valuesort :: Ord a => [a] -> [a]
#

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
Example1 expression
sort [1,6,4,3,2,5][1,2,3,4,5,6]
Example1 expression
sort "haskell""aehklls"
Example2 expressions
import Data.Semigroup(Arg(..))sort [Arg ":)" 0, Arg ":D" 0, Arg ":)" 1, Arg ":3" 0, Arg ":D" 1][Arg ":)" 0,Arg ":)" 1,Arg ":3" 0,Arg ":D" 0,Arg ":D" 1]
valueintersect :: Eq a => [a] -> [a] -> [a]
#

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
Example1 expression
[1,2,3,4] `intersect` [2,4,6,8][2,4]

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:

Example2 expressions
import Data.Semigroupintersect [Arg () "dog"] [Arg () "cow", Arg () "cat"][Arg () "dog"]

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

Example2 expressions
"coot" `intersect` "heron""oo""heron" `intersect` "coot""o"

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:

Example4 expressions
intersect [100..] [0..][100,101,102,103...intersect [0] [1..]* Hangs forever *intersect [1..] [0]* Hangs forever *intersect (cycle [1..3]) [2][2,2,2,2...
valuedropWhileEnd :: (a -> Bool) -> [a] -> [a]
#

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:

Example1 expression
take 1 (dropWhileEnd (< 0) (1 : undefined))[1]
Example1 expression
take 1 (reverse $ dropWhile (< 0) $ reverse (1 : undefined))*** Exception: Prelude.undefined

but on the other hand

Example1 expression
last (dropWhileEnd (< 0) [undefined, 1])*** Exception: Prelude.undefined
Example1 expression
last (reverse $ dropWhile (< 0) $ reverse [undefined, 1])1
Examples
Example1 expression
dropWhileEnd isSpace "foo\n""foo"
Example2 expressions
dropWhileEnd isSpace "foo bar""foo bar"dropWhileEnd (> 10) [1..20][1,2,3,4,5,6,7,8,9,10]
valuestripPrefix :: Eq a => [a] -> [a] -> Maybe [a]
#

\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
Example1 expression
stripPrefix "foo" "foobar"Just "bar"
Example1 expression
stripPrefix "foo" "foo"Just ""
Example1 expression
stripPrefix "foo" "barfoo"Nothing
Example1 expression
stripPrefix "foo" "barfoobaz"Nothing
valuegroupBy :: (a -> a -> Bool) -> [a] -> [[a]]
#

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:

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

It's often preferable to use Data.List.NonEmpty.groupBy, which provides type-level guarantees of non-emptiness of inner lists.

Examples
Example1 expression
groupBy (/=) [1, 1, 1, 2, 3, 1, 4, 4, 5][[1],[1],[1,2,3],[1,4,4,5]]
Example1 expression
groupBy (>) [1, 3, 5, 1, 4, 2, 6, 5, 4][[1],[3],[5,1,4,2],[6,5,4]]
Example1 expression
groupBy (const not) [True, False, True, False, False, False, True][[True,False],[True,False,False,False],[True]]
valuenubBy :: (a -> a -> Bool) -> [a] -> [a]
#

The nubBy function behaves just like nub, except it uses a user-supplied equality predicate instead of the overloaded (==) function.

Examples
Example1 expression
nubBy (\x y -> mod x 3 == mod y 3) [1,2,4,5,6][1,2,6]
Example1 expression
nubBy (/=) [2, 7, 1, 8, 2, 8, 1, 8, 2, 8][2,2,2]
Example1 expression
nubBy (>) [1, 2, 3, 2, 1, 5, 4, 5, 3, 2][1,2,3,5,5]
valuesortBy :: (a -> a -> Ordering) -> [a] -> [a]
#

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
Example1 expression
sortBy (\(a,_) (b,_) -> compare a b) [(2, "world"), (4, "!"), (1, "Hello")][(1,"Hello"),(2,"world"),(4,"!")]
valueisPrefixOf :: Eq a => [a] -> [a] -> Bool
#

\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
Example1 expression
"Hello" `isPrefixOf` "Hello World!"True
Example1 expression
"Hello" `isPrefixOf` "Wello Horld!"False

For the result to be True, the first list must be finite; False, however, results from any mismatch:

Example1 expression
[0..] `isPrefixOf` [1..]False
Example1 expression
[0..] `isPrefixOf` [0..99]False
Example1 expression
[0..99] `isPrefixOf` [0..]True
Example1 expression
[0..] `isPrefixOf` [0..]* Hangs forever *

isPrefixOf shortcuts when the first argument is empty:

Example1 expression
isPrefixOf [] undefinedTrue
valuefind :: Foldable t => (a -> Bool) -> t a -> Maybe a
#

The find function takes a predicate and a structure and returns the leftmost element of the structure matching the predicate, or Nothing if there is no such element.

Examples

Basic usage:

Example1 expression
find (> 42) [0, 5..]Just 45
Example1 expression
find (> 12) [1..7]Nothing
valuemaximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
#

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

Examples

Basic usage:

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

WARNING: This function is partial for possibly-empty structures like lists.

valueminimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
#

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

Examples

Basic usage:

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

WARNING: This function is partial for possibly-empty structures like lists.

valueisSubsequenceOf :: Eq a => [a] -> [a] -> Bool
#

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.

isSubsequenceOf x y is equivalent to x `elem` (subsequences y).

Note: isSubsequenceOf is often used in infix form.

Examples
Example1 expression
"GHC" `isSubsequenceOf` "The Glorious Haskell Compiler"True
Example1 expression
['a','d'..'z'] `isSubsequenceOf` ['a'..'z']True
Example1 expression
[1..10] `isSubsequenceOf` [10,9..0]False

For the result to be True, the first list must be finite; for the result to be False, the second list must be finite:

Example1 expression
[0,2..10] `isSubsequenceOf` [0..]True
Example1 expression
[0..] `isSubsequenceOf` [0,2..10]False
Example1 expression
[0,2..] `isSubsequenceOf` [0..]* Hangs forever*
value(\\) :: Eq a => [a] -> [a] -> [a]
#

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
Example1 expression
"Hello World!" \\ "ell W""Hoorld!"

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

Example1 expression
take 5 ([0..] \\ [2..4])[0,1,5,6,7]
Example1 expression
take 5 ([0..] \\ [2..])* Hangs forever *
valuedelete :: Eq a => a -> [a] -> [a]
#

\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
Example1 expression
delete 'a' "banana""bnana"
Example1 expression
delete "not" ["haskell", "is", "not", "awesome"]["haskell","is","awesome"]
valuedeleteBy :: (a -> a -> Bool) -> a -> [a] -> [a]
#

\mathcal{O}(n). The deleteBy function behaves like delete, but takes a user-supplied equality predicate.

Examples
Example1 expression
deleteBy (<=) 4 [1..10][1,2,3,5,6,7,8,9,10]
Example1 expression
deleteBy (/=) 5 [5, 5, 4, 3, 5, 2][5,5,3,5,2]
valuedeleteFirstsBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
#

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
Example1 expression
deleteFirstsBy (>) [1..10] [3, 4, 5][4,5,6,7,8,9,10]
Example1 expression
deleteFirstsBy (/=) [1..10] [1, 3, 5][4,5,6,7,8,9,10]
valueelemIndex :: Eq a => a -> [a] -> Maybe Int
#

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
Example1 expression
elemIndex 4 [0..]Just 4
Example1 expression
elemIndex 'o' "haskell"Nothing
Example1 expression
elemIndex 0 [1..]* hangs forever *
valueelemIndices :: Eq a => a -> [a] -> [Int]
#

The elemIndices function extends elemIndex, by returning the indices of all elements equal to the query element, in ascending order.

Examples
Example1 expression
elemIndices 'o' "Hello World"[4,7]
Example1 expression
elemIndices 1 [1, 2, 3, 1, 2, 3][0,3]
valuefindIndex :: (a -> Bool) -> [a] -> Maybe Int
#

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
Example1 expression
findIndex isSpace "Hello World!"Just 5
Example1 expression
findIndex odd [0, 2, 4, 6]Nothing
Example1 expression
findIndex even [1..]Just 1
Example1 expression
findIndex odd [0, 2 ..]* hangs forever *
valuefindIndices :: (a -> Bool) -> [a] -> [Int]
#

The findIndices function extends findIndex, by returning the indices of all elements satisfying the predicate, in ascending order.

Examples
Example1 expression
findIndices (`elem` "aeiou") "Hello World!"[1,4,7]
Example1 expression
findIndices (\l -> length l > 3) ["a", "bcde", "fgh", "ijklmnop"][1,3]
valuegenericLength :: Num i => [a] -> i
#

\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
Example2 expressions
genericLength [1, 2, 3] :: Int3genericLength [1, 2, 3] :: Float3.0

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.

Example1 expression
genericLength [1..200] :: Int8-56
valueinits :: [a] -> [[a]]
#

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

inits is semantically equivalent to map reverse . scanl (flip (:)) [], but under the hood uses a queue to amortize costs of reverse.

Laziness

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

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

Examples
Example1 expression
inits "abc"["","a","ab","abc"]
Example1 expression
inits [][[]]

inits is productive on infinite lists:

Example1 expression
take 5 $ inits [1..][[],[1],[1,2],[1,2,3],[1,2,3,4]]
valueinsert :: Ord a => a -> [a] -> [a]
#

\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
Example1 expression
insert (-1) [1, 2, 3][-1,1,2,3]
Example1 expression
insert 'd' "abcefg""abcdefg"
Example1 expression
insert 4 [1, 2, 3, 5, 6, 7][1,2,3,4,5,6,7]
valueinsertBy :: (a -> a -> Ordering) -> a -> [a] -> [a]
#

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

Examples
Example1 expression
insertBy (\x y -> compare (length x) (length y)) [1, 2] [[1], [1, 2, 3], [1, 2, 3, 4]][[1],[1,2],[1,2,3],[1,2,3,4]]
valueintercalate :: [a] -> [[a]] -> [a]
#

intercalate xs xss is equivalent to (concat (intersperse xs xss)). It inserts the list xs in between the lists in xss and concatenates the result.

Laziness

intercalate has the following properties:

Example1 expression
take 5 (intercalate undefined ("Lorem" : undefined))"Lorem"
Example1 expression
take 6 (intercalate ", " ("Lorem" : undefined))"Lorem*** Exception: Prelude.undefined
Examples
Example1 expression
intercalate ", " ["Lorem", "ipsum", "dolor"]"Lorem, ipsum, dolor"
Example1 expression
intercalate [0, 1] [[2, 3], [4, 5, 6], []][2,3,0,1,4,5,6,0,1]
Example1 expression
intercalate [1, 2, 3] [[], []][1,2,3]
valueintersectBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
#

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.

valueintersperse :: a -> [a] -> [a]
#

\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

Example1 expression
take 1 (intersperse undefined ('a' : undefined))"a"
Example1 expression
take 2 (intersperse ',' ('a' : undefined))"a*** Exception: Prelude.undefined
Examples
Example1 expression
intersperse ',' "abcde""a,b,c,d,e"
Example1 expression
intersperse 1 [3, 4, 5][3,1,4,1,5]
valueisInfixOf :: Eq a => [a] -> [a] -> Bool
#

The isInfixOf function takes two lists and returns True iff the first list is contained, wholly and intact, anywhere within the second.

Examples
Example1 expression
isInfixOf "Haskell" "I really like Haskell."True
Example1 expression
isInfixOf "Ial" "I really like Haskell."False

For the result to be True, the first list must be finite; for the result to be False, the second list must be finite:

Example1 expression
[20..50] `isInfixOf` [0..]True
Example1 expression
[0..] `isInfixOf` [20..50]False
Example1 expression
[0..] `isInfixOf` [0..]* Hangs forever *
valuenub :: Eq a => [a] -> [a]
#

\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
Example1 expression
nub [1,2,3,4,3,2,1,2,4,3,5][1,2,3,4,5]
Example1 expression
nub "hello, world!""helo, wrd!"
valuepartition :: (a -> Bool) -> [a] -> ([a], [a])
#

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
Example1 expression
partition (`elem` "aeiou") "Hello World!"("eoo","Hll Wrld!")
Example1 expression
partition even [1..10]([2,4,6,8,10],[1,3,5,7,9])
Example1 expression
partition (< 5) [1..10]([1,2,3,4],[5,6,7,8,9,10])
valuepermutations :: [a] -> [[a]]
#

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 permutations xs starts with those permutations that permute take n xs and keep drop n xs.

Examples
Example1 expression
permutations "abc"["abc","bac","cba","bca","cab","acb"]
Example1 expression
permutations [1, 2][[1,2],[2,1]]
Example1 expression
permutations [][[]]

This function is productive on infinite inputs:

Example1 expression
take 6 $ map (take 3) $ permutations ['a'..]["abc","bac","cba","bca","cab","acb"]
valuesingleton :: a -> [a]
#

Construct a list from a single element.

Examples
Example1 expression
singleton True[True]
Example1 expression
singleton [1, 2, 3][[1,2,3]]
Example1 expression
singleton 'c'"c"
valuesubsequences :: [a] -> [[a]]
#

The subsequences function returns the list of all subsequences of the argument.

Laziness

subsequences does not look ahead unless it must:

Example2 expressions
take 1 (subsequences undefined)[[]]take 2 (subsequences ('a' : undefined))["","a"]
Examples
Example1 expression
subsequences "abc"["","a","b","ab","c","ac","bc","abc"]

This function is productive on infinite inputs:

Example1 expression
take 8 $ subsequences ['a'..]["","a","b","ab","c","ac","bc","abc"]
valuetails :: [a] -> [[a]]
#

\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 _|_ = _|_ : _|_

Example1 expression
tails undefined[*** Exception: Prelude.undefined
Example1 expression
drop 1 (tails [undefined, 1, 2])[[1, 2], [2], []]
Examples
Example1 expression
tails "abc"["abc","bc","c",""]
Example1 expression
tails [1, 2, 3][[1,2,3],[2,3],[3],[]]
Example1 expression
tails [][[]]
valuetranspose :: [[a]] -> [[a]]
#

The transpose function transposes the rows and columns of its argument.

Laziness

transpose is lazy in its elements

Example1 expression
take 1 (transpose ['a' : undefined, 'b' : undefined])["ab"]
Examples
Example1 expression
transpose [[1,2,3],[4,5,6]][[1,4],[2,5],[3,6]]

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

Example1 expression
transpose [[10,11],[20],[],[30,31,32]][[10,20,30],[11,31],[32]]

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

Example1 expression
transpose (repeat [])* Hangs forever *
valueunfoldr :: (b -> Maybe (a, b)) -> b -> [a]
#

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
Example1 expression
take 1 (unfoldr (\x -> Just (x, undefined)) 'a')"a"
Examples
Example1 expression
unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10[10,9,8,7,6,5,4,3,2,1]
Example1 expression
take 10 $ unfoldr (\(x, y) -> Just (x, (y, x + y))) (0, 1)[0,1,1,2,3,5,8,13,21,54]
valueunzip4 :: [(a, b, c, d)] -> ([a], [b], [c], [d])
#

The unzip4 function takes a list of quadruples and returns four lists, analogous to unzip.

valueunzip5 :: [(a, b, c, d, e)] -> ([a], [b], [c], [d], [e])
#

The unzip5 function takes a list of five-tuples and returns five lists, analogous to unzip.

valueunzip6 :: [(a, b, c, d, e, f)] -> ([a], [b], [c], [d], [e], [f])
#

The unzip6 function takes a list of six-tuples and returns six lists, analogous to unzip.

valueunzip7 :: [(a, b, c, d, e, f, g)] -> ([a], [b], [c], [d], [e], [f], [g])
#

The unzip7 function takes a list of seven-tuples and returns seven lists, analogous to unzip.

valuezip4 :: [a] -> [b] -> [c] -> [d] -> [(a, b, c, d)]
#

The zip4 function takes four lists and returns a list of quadruples, analogous to zip. It is capable of list fusion, but it is restricted to its first list argument and its resulting list.

valuezip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a, b, c, d, e)]
#

The zip5 function takes five lists and returns a list of five-tuples, analogous to zip. It is capable of list fusion, but it is restricted to its first list argument and its resulting list.

valuezip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a, b, c, d, e, f)]
#

The zip6 function takes six lists and returns a list of six-tuples, analogous to zip. It is capable of list fusion, but it is restricted to its first list argument and its resulting list.

valuezip7
  1. :: [a]
  2. -> [b]
  3. -> [c]
  4. -> [d]
  5. -> [e]
  6. -> [f]
  7. -> [g]
  8. -> [(a, b, c, d, e, f, g)]
#

The zip7 function takes seven lists and returns a list of seven-tuples, analogous to zip. It is capable of list fusion, but it is restricted to its first list argument and its resulting list.

valuezipWith4 :: (a -> b -> c -> d -> e) -> [a] -> [b] -> [c] -> [d] -> [e]
#

The zipWith4 function takes a function which combines four elements, as well as four lists and returns a list of their point-wise combination, analogous to zipWith. It is capable of list fusion, but it is restricted to its first list argument and its resulting list.

valuezipWith5
  1. :: a -> b -> c -> d -> e -> f
  2. -> [a]
  3. -> [b]
  4. -> [c]
  5. -> [d]
  6. -> [e]
  7. -> [f]
#

The zipWith5 function takes a function which combines five elements, as well as five lists and returns a list of their point-wise combination, analogous to zipWith. It is capable of list fusion, but it is restricted to its first list argument and its resulting list.

valuezipWith6
  1. :: a -> b -> c -> d -> e -> f -> g
  2. -> [a]
  3. -> [b]
  4. -> [c]
  5. -> [d]
  6. -> [e]
  7. -> [f]
  8. -> [g]
#

The zipWith6 function takes a function which combines six elements, as well as six lists and returns a list of their point-wise combination, analogous to zipWith. It is capable of list fusion, but it is restricted to its first list argument and its resulting list.

valuezipWith7
  1. :: a -> b -> c -> d -> e -> f -> g -> h
  2. -> [a]
  3. -> [b]
  4. -> [c]
  5. -> [d]
  6. -> [e]
  7. -> [f]
  8. -> [g]
  9. -> [h]
#

The zipWith7 function takes a function which combines seven elements, as well as seven lists and returns a list of their point-wise combination, analogous to zipWith. It is capable of list fusion, but it is restricted to its first list argument and its resulting list.

valuemapAccumL :: Traversable t => (s -> a -> (s, b)) -> s -> t a -> (s, t b)
#

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:

Example1 expression
mapAccumL (\a b -> (a + b, a)) 0 [1..10](55,[0,1,3,6,10,15,21,28,36,45])
Example1 expression
mapAccumL (\a b -> (a <> show b, a)) "0" [1..5]("012345",["0","01","012","0123","01234"])
valuemapAccumR :: Traversable t => (s -> a -> (s, b)) -> s -> t a -> (s, t b)
#

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:

Example1 expression
mapAccumR (\a b -> (a + b, a)) 0 [1..10](55,[54,52,49,45,40,34,27,19,10,0])
Example1 expression
mapAccumR (\a b -> (a <> show b, a)) "0" [1..5]("054321",["05432","0543","054","05","0"])
valueiterate' :: (a -> a) -> a -> [a]
#

iterate' is the strict version of iterate.

It forces the result of each application of the function to weak head normal form (WHNF) before proceeding.

Example1 expression
take 1 $ iterate' undefined 42*** Exception: Prelude.undefined
valuescanl' :: (b -> a -> b) -> b -> [a] -> [b]
#

\mathcal{O}(n). A strict version of scanl.

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

\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 Just (x, xs), where x is the head of the list and xs its tail.

Examples
Example1 expression
uncons []Nothing
Example1 expression
uncons [1]Just (1,[])
Example1 expression
uncons [1, 2, 3]Just (1,[2,3])

String operations

11 declarations
valuelower :: String -> String
#

Convert a string to lower case.

lower "This is A TEST" == "this is a test"
lower "" == ""
valueupper :: String -> String
#

Convert a string to upper case.

upper "This is A TEST" == "THIS IS A TEST"
upper "" == ""
valuetrim :: String -> String
#

Remove spaces from either side of a string. A combination of trimEnd and trimStart.

trim      "  hello   " == "hello"
trimStart "  hello   " == "hello   "
trimEnd   "  hello   " == "  hello"
\s -> trim s == trimEnd (trimStart s)
valueword1 :: String -> (String, String)
#

Split the first word off a string. Useful for when starting to parse the beginning of a string, but you want to accurately preserve whitespace in the rest of the string.

word1 "" == ("", "")
word1 "keyword rest of string" == ("keyword","rest of string")
word1 "  keyword\n  rest of string" == ("keyword","rest of string")
\s -> fst (word1 s) == concat (take 1 $ words s)
\s -> words (snd $ word1 s) == drop 1 (words s)
valueline1 :: String -> (String, String)
#

Split the first line off a string.

line1 "" == ("", "")
line1 "test" == ("test","")
line1 "test\n" == ("test","")
line1 "test\nrest" == ("test","rest")
line1 "test\nrest\nmore" == ("test","rest\nmore")
valueescapeHTML :: String -> String
#

Escape a string such that it can be inserted into an HTML document or " attribute without any special interpretation. This requires escaping the <, >, & and " characters. Note that it will escape " and ' even though that is not required in an HTML body (but is not harmful).

escapeHTML "this is a test" == "this is a test"
escapeHTML "<b>\"g&t\"</n>" == "&lt;b&gt;&quot;g&amp;t&quot;&lt;/n&gt;"
escapeHTML "t'was another test" == "t&#39;was another test"
valueescapeJSON :: String -> String
#

Escape a string so it can form part of a JSON literal. This requires escaping the special whitespace and control characters. Additionally, Note that it does not add quote characters around the string.

escapeJSON "this is a test" == "this is a test"
escapeJSON "\ttab\nnewline\\" == "\\ttab\\nnewline\\\\"
escapeJSON "\ESC[0mHello" == "\\u001b[0mHello"

Splitting

19 declarations
valuedropEnd :: Int -> [a] -> [a]
#

Drop a number of elements from the end of the list.

dropEnd 3 "hello"  == "he"
dropEnd 5 "bye"    == ""
dropEnd (-1) "bye" == "bye"
\i xs -> dropEnd i xs `isPrefixOf` xs
\i xs -> length (dropEnd i xs) == max 0 (length xs - max 0 i)
\i -> take 3 (dropEnd 5 [i..]) == take 3 [i..]
valuetakeEnd :: Int -> [a] -> [a]
#

Take a number of elements from the end of the list.

takeEnd 3 "hello"  == "llo"
takeEnd 5 "bye"    == "bye"
takeEnd (-1) "bye" == ""
\i xs -> takeEnd i xs `isSuffixOf` xs
\i xs -> length (takeEnd i xs) == min (max 0 i) (length xs)
valuesplitAtEnd :: Int -> [a] -> ([a], [a])
#

splitAtEnd n xs returns a split where the second element tries to contain n elements.

splitAtEnd 3 "hello" == ("he","llo")
splitAtEnd 3 "he"    == ("", "he")
\i xs -> uncurry (++) (splitAt i xs) == xs
\i xs -> splitAtEnd i xs == (dropEnd i xs, takeEnd i xs)
valuebreakEnd :: (a -> Bool) -> [a] -> ([a], [a])
#

Break, but from the end.

breakEnd isLower "youRE" == ("you","RE")
breakEnd isLower "youre" == ("youre","")
breakEnd isLower "YOURE" == ("","YOURE")
\f xs -> breakEnd (not . f) xs == spanEnd f  xs
valuespanEnd :: (a -> Bool) -> [a] -> ([a], [a])
#

Span, but from the end.

spanEnd isUpper "youRE" == ("you","RE")
spanEnd (not . isSpace) "x y z" == ("x y ","z")
\f xs -> uncurry (++) (spanEnd f xs) == xs
\f xs -> spanEnd f xs == swap (both reverse (span f (reverse xs)))
valuedropWhileEnd' :: (a -> Bool) -> [a] -> [a]
#

A version of dropWhileEnd but with different strictness properties. The function dropWhileEnd can be used on an infinite list and tests the property on each character. In contrast, dropWhileEnd' is strict in the spine of the list but only tests the trailing suffix. This version usually outperforms dropWhileEnd if the list is short or the test is expensive. Note the tests below cover both the prime and non-prime variants.

dropWhileEnd  isSpace "ab cde  " == "ab cde"
dropWhileEnd' isSpace "ab cde  " == "ab cde"
last (dropWhileEnd  even [undefined,3]) == undefined
last (dropWhileEnd' even [undefined,3]) == 3
head (dropWhileEnd  even (3:undefined)) == 3
head (dropWhileEnd' even (3:undefined)) == undefined
valuetakeWhileEnd :: (a -> Bool) -> [a] -> [a]
#

A version of takeWhile operating from the end.

takeWhileEnd even [2,3,4,6] == [4,6]
valuestripSuffix :: Eq a => [a] -> [a] -> Maybe [a]
#

Return the prefix of the second list if its suffix matches the entire first list.

Examples:

stripSuffix "bar" "foobar" == Just "foo"
stripSuffix ""    "baz"    == Just "baz"
stripSuffix "foo" "quux"   == Nothing
valuestripInfix :: Eq a => [a] -> [a] -> Maybe ([a], [a])
#

Return the the string before and after the search string, or Nothing if the search string is not present.

Examples:

stripInfix "::" "a::b::c" == Just ("a", "b::c")
stripInfix "/" "foobar"   == Nothing
valuestripInfixEnd :: Eq a => [a] -> [a] -> Maybe ([a], [a])
#

Similar to stripInfix, but searches from the end of the string.

stripInfixEnd "::" "a::b::c" == Just ("a::b", "c")
valuedropPrefix :: Eq a => [a] -> [a] -> [a]
#

Drops the given prefix from a list. It returns the original sequence if the sequence doesn't start with the given prefix.

dropPrefix "Mr. " "Mr. Men" == "Men"
dropPrefix "Mr. " "Dr. Men" == "Dr. Men"
valuedropSuffix :: Eq a => [a] -> [a] -> [a]
#

Drops the given suffix from a list. It returns the original sequence if the sequence doesn't end with the given suffix.

dropSuffix "!" "Hello World!"  == "Hello World"
dropSuffix "!" "Hello World!!" == "Hello World!"
dropSuffix "!" "Hello World."  == "Hello World."
valuewordsBy :: (a -> Bool) -> [a] -> [[a]]
#

A variant of words with a custom test. In particular, adjacent separators are discarded, as are leading or trailing separators.

wordsBy (== ':') "::xyz:abc::123::" == ["xyz","abc","123"]
\s -> wordsBy isSpace s == words s
valuelinesBy :: (a -> Bool) -> [a] -> [[a]]
#

A variant of lines with a custom test. In particular, if there is a trailing separator it will be discarded.

linesBy (== ':') "::xyz:abc::123::" == ["","","xyz","abc","","123",""]
\s -> linesBy (== '\n') s == lines s
linesBy (== ';') "my;list;here;" == ["my","list","here"]
valuebreakOn :: Eq a => [a] -> [a] -> ([a], [a])
#

Find the first instance of needle in haystack. The first element of the returned tuple is the prefix of haystack before needle is matched. The second is the remainder of haystack, starting with the match. If you want the remainder without the match, use stripInfix.

breakOn "::" "a::b::c" == ("a", "::b::c")
breakOn "/" "foobar"   == ("foobar", "")
\needle haystack -> let (prefix,match) = breakOn needle haystack in prefix ++ match == haystack
valuebreakOnEnd :: Eq a => [a] -> [a] -> ([a], [a])
#

Similar to breakOn, but searches from the end of the string.

The first element of the returned tuple is the prefix of haystack up to and including the last match of needle. The second is the remainder of haystack, following the match.

breakOnEnd "::" "a::b::c" == ("a::b::", "c")
valuesplitOn :: (Partial, Eq a) => [a] -> [a] -> [[a]]
#

Break a list into pieces separated by the first list argument, consuming the delimiter. An empty delimiter is invalid, and will cause an error to be raised.

splitOn "\r\n" "a\r\nb\r\nd\r\ne" == ["a","b","d","e"]
splitOn "aaa"  "aaaXaaaXaaaXaaa"  == ["","X","X","X",""]
splitOn "x"    "x"                == ["",""]
splitOn "x"    ""                 == [""]
\s x -> s /= "" ==> intercalate s (splitOn s x) == x
\c x -> splitOn [c] x                           == split (==c) x
valuesplit :: (a -> Bool) -> [a] -> [[a]]
#

Splits a list into components delimited by separators, where the predicate returns True for a separator element. The resulting components do not contain the separators. Two adjacent separators result in an empty component in the output.

split (== 'a') "aabbaca" == ["","","bb","c",""]
split (== 'a') ""        == [""]
split (== ':') "::xyz:abc::123::" == ["","","xyz","abc","","123","",""]
split (== ',') "my,list,here" == ["my","list","here"]
valuechunksOf :: Partial => Int -> [a] -> [[a]]
#

Split a list into chunks of a given size. The last chunk may contain fewer than n elements. The chunk size must be positive.

chunksOf 3 "my test" == ["my ","tes","t"]
chunksOf 3 "mytest"  == ["myt","est"]
chunksOf 8 ""        == []
chunksOf 0 "test"    == undefined

Basics

13 declarations
valueheadDef :: a -> [a] -> a
#

A total head with a default value.

headDef 1 []      == 1
headDef 1 [2,3,4] == 2
\x xs -> headDef x xs == fromMaybe x (listToMaybe xs)
valuelastDef :: a -> [a] -> a
#

A total last with a default value.

lastDef 1 []      == 1
lastDef 1 [2,3,4] == 4
\x xs -> lastDef x xs == last (x:xs)
value(!?) :: [a] -> Int -> Maybe a
#

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
Example1 expression
['a', 'b', 'c'] !? 0Just 'a'
Example1 expression
['a', 'b', 'c'] !? 2Just 'c'
Example1 expression
['a', 'b', 'c'] !? 3Nothing
Example1 expression
['a', 'b', 'c'] !? (-1)Nothing
valuenotNull :: [a] -> Bool
#

A composition of not and null.

notNull []  == False
notNull [1] == True
\xs -> notNull xs == not (null xs)
valuelist :: b -> (a -> [a] -> b) -> [a] -> b
#

Non-recursive transform over a list, like maybe.

list 1 (\v _ -> v - 2) [5,6,7] == 3
list 1 (\v _ -> v - 2) []      == 1
\nil cons xs -> maybe nil (uncurry cons) (uncons xs) == list nil cons xs
valueunsnoc :: [a] -> Maybe ([a], a)
#

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

  • If the list is empty, returns Nothing.

  • If the list is non-empty, returns Just (xs, x), where xs is the initial 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
Example1 expression
unsnoc []Nothing
Example1 expression
unsnoc [1]Just ([],1)
Example1 expression
unsnoc [1, 2, 3]Just ([1,2],3)
Laziness
Example1 expression
fst <$> unsnoc [undefined]Just []
Example1 expression
head . fst <$> unsnoc (1 : undefined)Just *** Exception: Prelude.undefined
Example1 expression
head . fst <$> unsnoc (1 : 2 : undefined)Just 1
valuecons :: a -> [a] -> [a]
#

Append an element to the start of a list, an alias for (:).

cons 't' "est" == "test"
\x xs -> uncons (cons x xs) == Just (x,xs)
valuesnoc :: [a] -> a -> [a]
#

Append an element to the end of a list, takes O(n) time.

snoc "tes" 't' == "test"
\xs x -> unsnoc (snoc xs x) == Just (xs,x)
valuedrop1 :: [a] -> [a]
#

Equivalent to drop 1, but likely to be faster and a single lexeme.

drop1 ""         == ""
drop1 "test"     == "est"
\xs -> drop 1 xs == drop1 xs
valuedropEnd1 :: [a] -> [a]
#

Equivalent to dropEnd 1, but likely to be faster and a single lexeme.

dropEnd1 ""         == ""
dropEnd1 "test"     == "tes"
\xs -> dropEnd 1 xs == dropEnd1 xs
valuemconcatMap :: Monoid b => (a -> b) -> [a] -> b
#

Version on concatMap generalised to a Monoid rather than just a list.

mconcatMap Sum [1,2,3] == Sum 6
\f xs -> mconcatMap f xs == concatMap f xs
valuecompareLength :: [a] -> Int -> Ordering
#

Use compareLength xs n as a safer and faster alternative to compare (length xs) n. Similarly, it's better to write compareLength xs 10 == LT instead of length xs < 10.

While length would force and traverse the entire spine of xs (which could even diverge if xs is infinite), compareLength traverses at most n elements to determine its result.

Example7 expressions
compareLength [] 0EQcompareLength [] 1LTcompareLength ['a'] 1EQcompareLength ['a', 'b'] 1GTcompareLength [0..] 100GTcompareLength undefined (-1)GTcompareLength ('a' : undefined) 0GT
valuecomparingLength :: (Foldable f1, Foldable f2) => f1 a -> f2 b -> Ordering
#

Lazily compare the length of two Foldables. > comparingLength [1,2,3] [False] == GT > comparingLength [1,2] "ab" == EQ > (xs :: [Int]) (ys :: [Int]) -> comparingLength xs ys == Data.Ord.comparing length xs ys > comparingLength 1,2 == LT > comparingLength (1:2:3:undefined) [1,2] == GT

Enum operations

1 declaration

List operations

34 declarations
valuegroupSort :: Ord k => [(k, v)] -> [(k, [v])]
#

A combination of group and sort.

groupSort [(1,'t'),(3,'t'),(2,'e'),(2,'s')] == [(1,"t"),(2,"es"),(3,"t")]
\xs -> map fst (groupSort xs) == sort (nub (map fst xs))
\xs -> concatMap snd (groupSort xs) == map snd (sortOn fst xs)
valuegroupSortOn :: Ord b => (a -> b) -> [a] -> [[a]]
#

A combination of group and sort, using a part of the value to compare on.

groupSortOn length ["test","of","sized","item"] == [["of"],["test","item"],["sized"]]
valuegroupSortBy :: (a -> a -> Ordering) -> [a] -> [[a]]
#

A combination of group and sort, using a predicate to compare on.

groupSortBy (compare `on` length) ["test","of","sized","item"] == [["of"],["test","item"],["sized"]]
valuenubOrd :: Ord a => [a] -> [a]
#

O(n log n). The nubOrd function removes duplicate elements from a list. In particular, it keeps only the first occurrence of each element. Unlike the standard nub operator, this version requires an Ord instance and consequently runs asymptotically faster.

nubOrd "this is a test" == "this ae"
nubOrd (take 4 ("this" ++ undefined)) == "this"
\xs -> nubOrd xs == nub xs
valuenubOrdBy :: (a -> a -> Ordering) -> [a] -> [a]
#

A version of nubOrd with a custom predicate.

nubOrdBy (compare `on` length) ["a","test","of","this"] == ["a","test","of"]
valuenubOrdOn :: Ord b => (a -> b) -> [a] -> [a]
#

A version of nubOrd which operates on a portion of the value.

nubOrdOn length ["a","test","of","this"] == ["a","test","of"]
valuenubOn :: Eq b => (a -> b) -> [a] -> [a]
#

Deprecated. Use nubOrdOn, since this function is O(n^2)

DEPRECATED Use nubOrdOn, since this function is _O(n^2)_.

A version of nub where the equality is done on some extracted value. nubOn f is equivalent to nubBy ((==) on f), but has the performance advantage of only evaluating f once for each element in the input list.

valuegroupOn :: Eq k => (a -> k) -> [a] -> [[a]]
#

A version of group where the equality is done on some extracted value.

groupOn abs [1,-1,2] == [[1,-1], [2]]
valuegroupOnKey :: Eq k => (a -> k) -> [a] -> [(k, [a])]
#

A version of groupOn which pairs each group with its "key" - the extracted value used for equality testing.

groupOnKey abs [1,-1,2] == [(1, [1,-1]), (2, [2])]
valuenubSort :: Ord a => [a] -> [a]
#

O(n log n). The nubSort function sorts and removes duplicate elements from a list. In particular, it keeps only the first occurrence of each element.

nubSort "this is a test" == " aehist"
\xs -> nubSort xs == nub (sort xs)
valuenubSortBy :: (a -> a -> Ordering) -> [a] -> [a]
#

A version of nubSort with a custom predicate.

nubSortBy (compare `on` length) ["a","test","of","this"] == ["a","of","test"]
valuenubSortOn :: Ord b => (a -> b) -> [a] -> [a]
#

A version of nubSort which operates on a portion of the value.

nubSortOn length ["a","test","of","this"] == ["a","of","test"]
valuemaximumOn :: (Partial, Ord b) => (a -> b) -> [a] -> a
#

A version of maximum where the comparison is done on some extracted value. Raises an error if the list is empty. Only calls the function once per element.

maximumOn id [] == undefined
maximumOn length ["test","extra","a"] == "extra"
valueminimumOn :: (Partial, Ord b) => (a -> b) -> [a] -> a
#

A version of minimum where the comparison is done on some extracted value. Raises an error if the list is empty. Only calls the function once per element.

minimumOn id [] == undefined
minimumOn length ["test","extra","a"] == "a"
valuesum' :: Num a => [a] -> a
#

A strict version of sum. Unlike sum this function is always strict in the Num argument, whereas the standard version is only strict if the optimiser kicks in.

sum' [1, 2, 3] == 6
valuesumOn' :: Num b => (a -> b) -> [a] -> b
#

A strict version of sum, using a custom valuation function.

sumOn' read ["1", "2", "3"] == 6
valueproductOn' :: Num b => (a -> b) -> [a] -> b
#

A strict version of product, using a custom valuation function.

productOn' read ["1", "2", "4"] == 8
valuedisjoint :: Eq a => [a] -> [a] -> Bool
#

Are two lists disjoint, with no elements in common.

disjoint [1,2,3] [4,5] == True
disjoint [1,2,3] [4,1] == False
valuedisjointOrd :: Ord a => [a] -> [a] -> Bool
#

O((m+n) log m), m <= n. Are two lists disjoint, with no elements in common.

disjointOrd is more strict than disjoint. For example, disjointOrd cannot terminate if both lists are infinite, while disjoint can.

disjointOrd [1,2,3] [4,5] == True
disjointOrd [1,2,3] [4,1] == False
valuedisjointOrdBy :: (a -> a -> Ordering) -> [a] -> [a] -> Bool
#

A version of disjointOrd with a custom predicate.

disjointOrdBy (compare `on` (`mod` 7)) [1,2,3] [4,5] == True
disjointOrdBy (compare `on` (`mod` 7)) [1,2,3] [4,8] == False
valueallSame :: Eq a => [a] -> Bool
#

Are all elements the same.

allSame [1,1,2] == False
allSame [1,1,1] == True
allSame [1]     == True
allSame []      == True
allSame (1:1:2:undefined) == False
\xs -> allSame xs == (length (nub xs) <= 1)
valueanySame :: Eq a => [a] -> Bool
#

Is there any element which occurs more than once.

anySame [1,1,2] == True
anySame [1,2,3] == False
anySame (1:2:1:undefined) == True
anySame [] == False
\xs -> anySame xs == (length (nub xs) < length xs)
valuerepeatedly :: ([a] -> (b, [a])) -> [a] -> [b]
#

Apply some operation repeatedly, producing an element of output and the remainder of the list.

When the empty list is reached it is returned, so the operation is never applied to the empty input. That fact is encoded in the type system with repeatedlyNE

\xs -> repeatedly (splitAt 3) xs  == chunksOf 3 xs
\xs -> repeatedly word1 (trim xs) == words xs
\xs -> repeatedly line1 xs == lines xs
valuerepeatedlyNE :: (NonEmpty a -> (b, [a])) -> [a] -> [b]
#

Apply some operation repeatedly, producing an element of output and the remainder of the list.

Identical to repeatedly, but has a more precise type signature.

valuefirstJust :: (a -> Maybe b) -> [a] -> Maybe b
#

Find the first element of a list for which the operation returns Just, along with the result of the operation. Like find but useful where the function also computes some expensive information that can be reused. Particular useful when the function is monadic, see firstJustM.

firstJust id [Nothing,Just 3]  == Just 3
firstJust id [Nothing,Nothing] == Nothing
valueconcatUnzip :: [([a], [b])] -> ([a], [b])
#

A merging of unzip and concat.

concatUnzip [("a","AB"),("bc","C")] == ("abc","ABC")
valueconcatUnzip3 :: [([a], [b], [c])] -> ([a], [b], [c])
#

A merging of unzip3 and concat.

concatUnzip3 [("a","AB",""),("bc","C","123")] == ("abc","ABC","123")
valuezipFrom :: Enum a => a -> [b] -> [(a, b)]
#

zip against an enumeration. Truncates the output if the enumeration runs out.

\i xs -> zip [i..] xs == zipFrom i xs
zipFrom False [1..3] == [(False,1),(True, 2)]
valuezipWithFrom :: Enum a => (a -> b -> c) -> a -> [b] -> [c]
#

zipFrom generalised to any combining operation. Truncates the output if the enumeration runs out.

\i xs -> zipWithFrom (,) i xs == zipFrom i xs
valuezipWithLongest :: (Maybe a -> Maybe b -> c) -> [a] -> [b] -> [c]
#

Like zipWith, but keep going to the longest value. The function argument will always be given at least one Just, and while both lists have items, two Just values.

zipWithLongest (,) "a" "xyz" == [(Just 'a', Just 'x'), (Nothing, Just 'y'), (Nothing, Just 'z')]
zipWithLongest (,) "a" "x" == [(Just 'a', Just 'x')]
zipWithLongest (,) "" "x" == [(Nothing, Just 'x')]
valuereplace :: Eq a => [a] -> [a] -> [a] -> [a]
#

Replace a subsequence everywhere it occurs.

replace "el" "_" "Hello Bella" == "H_lo B_la"
replace "el" "e" "Hello"       == "Helo"
replace "" "x" "Hello"         == "xHxexlxlxox"
replace "" "x" ""              == "x"
\xs ys -> replace xs xs ys == ys
valuemerge :: Ord a => [a] -> [a] -> [a]
#

Merge two lists which are assumed to be ordered.

merge "ace" "bd" == "abcde"
\xs ys -> merge (sort xs) (sort ys) == sort (xs ++ ys)
valuemergeBy :: (a -> a -> Ordering) -> [a] -> [a] -> [a]
#

Like merge, but with a custom ordering function.