Lists
Chapter 4 of 9Many values of one type, and how to work with them.
Many values of the same type
A list holds any number of values of the same type:
A list never changes. Every list function gives you a new list. The three you will use most:
mapchanges every item.filterkeeps the items that pass a test.foldlwalks the list and keeps a running result, starting from0here, and adds each item to it. Thelis for left: it starts from the left.
Some lists have nothing to give. What is the first item of []? Bert does not crash. It answers with a value that says so:
Those Ok and Err values are called variants. They are next.
More list functions, such as List.reverse, List.concat, List.any and List.sort, are in the docs. There is no range or "repeat N times" helper. To count, you write a function that calls itself, as in Functions.
Chaining with |>
Say you want to keep the even numbers, times them by ten, and add them up. Nested calls read inside out:
The pipe |> lets you write the same thing top to bottom:
- The value goes in as the first argument.
x |> f(a)isf(x, a). - Right after a
|>, and only there,f()andfmean the same thing:nums |> List.lengthandnums |> List.length()are bothList.length(nums). - Use
|>when you have two or more steps; one step is just a normal call.