Haskell List Operations
List operations are ready-made functions that measure, check, and rearrange a list. Each operation returns a value or a new list and leaves the original list unchanged.
Length, sum and product summarise a list
The three results are the length, the sum, and the product, in that order.
main :: IO ()
main = print [length [4, 2, 9, 5], sum [4, 2, 9, 5], product [4, 2, 9, 5]]Maximum, minimum and last pick single values
The three results are the maximum, the minimum, and the last value, in that order.
main :: IO ()
main = print [maximum [4, 2, 9, 5], minimum [4, 2, 9, 5], last [4, 2, 9, 5]]Null and elem answer questions about a list
The results show that the list is not empty, that 9 is in it, and that 7 is not, in that order.
main :: IO ()
main = print [null [4, 2, 9, 5], elem 9 [4, 2, 9, 5], elem 7 [4, 2, 9, 5]]Take, drop, reverse and init reshape a list
The four results are take 2, drop 2, reverse, and init, in that order.
main :: IO ()
main = print [take 2 [4, 2, 9, 5], drop 2 [4, 2, 9, 5], reverse [4, 2, 9, 5], init [4, 2, 9, 5]]Example
main :: IO ()
main = print [sum (take 3 [10, 20, 30, 40]), maximum (drop 1 [10, 20, 30, 40])]Key points
- Length function: length gives how many values a list holds.
- Null function: null returns True when a list is empty.
- Elem function: elem, written before its value and its list, reports whether the value appears in the list.
- Totals: sum adds the numbers in a list and product multiplies them.
- Extremes: maximum gives the largest number in a list and minimum gives the smallest.
- Take and drop functions: take keeps the first values of a list and drop removes those first values.
In this example, take 3 keeps [10, 20, 30] and sum turns it into 60. Then drop 1 leaves [20, 30, 40] and maximum picks 40, so print shows both results in one list.
Note
last gives the final value, init gives all but the final value, and reverse puts the values in opposite order.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What is the value of drop 2 [10, 20, 30, 40]?