# Lists ## List literals A list with a constant length can be written by closing the list elements in brackets and separating the elements by commas: [1,2,3] [] ## List comprehension Lists can be formed with list comprehension expressions that resemble set comprehension in mathematics. For example [x+1 | x <- lst] creates a list of all elements in `lst` increased by one and [x+y | x <- lstX, y <- lstY] creates list of all sums of pairs where one element is in `lstX` and one in `lstY`. Note that the list may contain duplicates. It is possible to add also constraints [x `div` 2 | x <- lst, x `mod` 2 == 0] and definitions [x*y | x <- lst, y = x+1] Formally, a list comprehension expression is [ | , ..., ] where list qualifier can be one of the following * generator ` <- ` * guard `` * definition ` = ` * `then by ` The last type of qualifier can be used to make operations that affects the whole list, for example then drop 3 removes the first three elements and then sortBy by x sorts the elements by `x`. ## Accessing the list elements The most basic way of reading list is to read it element by element. ::value[Prelude/!] ::value[Prelude/length] ## Comparison Lists like almost all other types support the generic equality and comparison operations: ::value[Prelude/==,Prelude/!=] ::value[Prelude/<,Prelude/<=,Prelude/>,Prelude/>=] For example `lst == []` tests whether the `lst` is empty. The comparison of the list is lexicographic. ## Executing code for each list element The only difference between the following iteration functions is the order of their parameters: ::value[Prelude/iter, Prelude/for] ## Concatenating lists ::value[Prelude/+, Prelude/sum] ## List transformations ::value[Prelude/map] ::value[Prelude/filter] ::value[Prelude/join] ::value[Prelude/concatMap] ::value[Prelude/mapMaybe] ::value[Prelude/zip] ::value[Prelude/zipWith] ::value[Prelude/unzip] ## Ordering The following functions modify the order of the list elements: ::value[Prelude/sort, Prelude/sortBy, Prelude/sortWith] ::value[Prelude/reverse] ## Sublists The following functions extract some sublist of the given list: ::value[Prelude/take] ::value[Prelude/drop] ::value[Prelude/sub] ## Aggregate operations Sometimes it is necessary to compute some kind of summary over all elements of a list. The most useful generic aggregate operation is `foldl`. ::value[Prelude/foldl] It is used to define many more specialized aggreate operations such as sum = foldl (+) 0 product = foldl (*) 1 maximum = foldl1 max There is a variant that traverses the list from right to left: ::value[Prelude/foldr] and a variant that that assumes that the list has at least one element: ::value[Prelude/foldl1]