Lists
You can represent the idea of a collection of values in Elm using a List. Any kind of value can go in a List. You can even have a List of Lists!
> [ 5, 6, 7 ]
[5,6,7] : List number
> [ ‘h’, ‘e’, ‘y’ ]
[‘h’,’e’,’y’] : List Char
> [ [1,2,3], [3,4,5], [6,7,8,9] ]
[[1,2],[3,4,5],[6,7,8,9]] : List (List number)
There's just one catch: all values in a List must have the same type. But you probably could have figured this out on your own--look what happens when you try making a list with mixed values.
> [ 1, 2, '3' ]
-- TYPE MISMATCH --------------------------------------------- repl-temp-000.elm
The 2nd and 3rd elements are different types of values.
5│ [ 1, 2, '3' ]
^^^
The 2nd element has this type:
number
But the 3rd is:
Char
Hint: All elements should be the same type of value so that we can iterate
through the list without running into unexpected values.
Many types of Lists
As you've seen from the type signatures of all the above lists, there is no single List type--only List number, List Char, List String, and so on. There's a potentially infinite number of List types!
This means that you can't use two different kinds of Lists where you need values to match types. For example, you'll run into an error if you try comparing different kinds of Lists with the equality operators:
> [ 1, 2, 3 ] == [ 3, 4, 5 ]
False : Bool
> [ 1, 2, 3 ] == [ 'a', 'b', 'c' ]
-- TYPE MISMATCH --------------------------------------------- repl-temp-000.elm
The right argument of (==) is causing a type mismatch.
5│ [ 1, 2, 3 ] == [ 'a', 'b', 'c' ]
^^^^^^^^^^^^^^^^^
(==) is expecting the right argument to be a:
List number
But the right argument is:
List Char
Wildcard type variables
Even an empty List has a two-part type signature.
> [ ]
[] : List a
That a is a type variable like number. Just like number, it tells us that this value can act as multiple different types. But a is even more generic than number--it can stand in for absolutely any value. Therefore, a List a can serve as a List number, List Char, List (List number) or any other kind of list.
> [ 1, 2, 3 ] == []
False : Bool
> [ 'a', 'b', 'c' ] == []
False : Bool
> [] == []
True : Bool
List operators
That ++ operator for concatenating Strings actually works with Lists, too.
> [ 1, 2, 3 ] ++ [ 4, 5, 6 ]
[1,2,3,4,5,6] : List number
An operator that’s used specifically with Lists is the :: cons operator. It makes a new list out of an existing list and a value you’d like to place at the beginning.
> 'a' :: [ 'b', 'c', 'd' ]
['a','b','c','d'] : List Char
> 1 :: [2, 3]
[1,2,3] : List number
> 1 :: 2 :: [3]
[1,2,3] : List number
> 1 :: 2 :: 3 :: []
[1,2,3] : List number