List in Elm

Ronn Ross
InstructorRonn Ross

Share this video with your friends

Send Tweet
Published 7 years ago
Updated 4 years ago

List are an important collection in Elm. In this lesson we learn to create list as well as apply functions to filter, add, and transform them.

[00:00] Lists hold a lot of functionality, and are important collections in Elm. Let's explore them in the REPL. We can start the REPL from the terminal by typing, "elm-repl." We can create an empty list by using empty brackets.

[00:15] We now have a list of type A. A is just a placeholder. Since the list is empty, Elm cannot infer the type of data within our list. Let's create another list with numbers. We now have a list of number. A list can also contain strings, but not both.

[00:42] Let's add a list to a value. Now, we have a list of numbers. We can start applying some functions to our list. We can check if a list is empty, check for the length of a list, check if a member exists within the list.

[01:07] Take gets the first N from a list. Add a member to the beginning of the list using the double colon pronounced cons. Collections are immutable, so if we look at the origin list, we see it as not changed. We have to assign it to a new value.

[01:30] Now, the order is off, so we can sort them. Note once again, we have not changed the value of diff list. There are several more functions we could apply to our list, like reverse, head, tail, drop. Let's use a map to iterate over our list and transform each value.

[01:52] Map takes two parameters, a function that we want to apply to each member of a list, and the list we want to work on. We will use an anonymous function to add one to each item in our list. The result is what we would expect, but if we wanted to keep the return value, we need to create a definition to hold the new list.

[02:15] We can filter items out of the list. Let's return items greater than two. There are many more handy functions to use on our list. We now have a solid foundation for working with lists in Elm.