3 Lists and Simple Data
Lists in Erlang and LFE are straight-forward; those coming from another programming language will not find anything surprising about them. Lists are generally good for storing and iterating over data that is of a similar type. There are other types one can use for more structured or complex data type combos.
You can create lists in LFE in the following ways:
To get the length of a list, you'll need to use the
length function from
Later, we will discuss Lisp-specific functions that have been implemented in LFE, but this is a good time to mention a few classic functions:
There is an Erlang module dedicated to handling lists that we can take advantage of:
You can also use the
++ operator to combine two lists:
map example that generates the same list we manually created
Another one is
filter, but before we use it, let's first define a
predicate that returns
true for even numbers:
Not let's try out
filter with our new predicate:
There are many, many more highly useful functions in the
lists module --
be sure to give the docs a thorough reading, lest you miss something fun!
3.1.1 I/O Lists
There is another type of list that is used for such things as file and network
operations; it's called an
IoList is a list whose
elements are either
* integers ranging from 0 to 255,
* a combination of these.
Here's an example for you:
You don't need to flatten
IoLists; they get passed as they are to the
various low-level functions that accept an
IoList and Erlang will flatten
them efficiently for you.
We saw an example of this in a previous section when we were playing with
strings as binaries. We ended up calling a function that accepted an
IoList as a parameter and this saved us from having to flatten the list
of binaries ourselves. If you recall,
data was a long string and the
split function returned a list of binaries:
Tuples are the data melting pot for Erlang: you can combine any of Erlang's data types (including lists and other tuples) into a single composite data type. This comes in very handy with pattern matching, but in general, makes passing data around much easier.
Creating a tuple can be as simple as:
But perhaps more useful:
You could also have done this:
Here's a simple data structure:
Now let's poke around at our new data structure:
Using the erlang module's function is one way to get our tuple data, but you'll probably not use that as much as the next method we show you.
We're going to sneak ahead here a bit, and touch on patterns again; we'll explain in more detail in the actual section on patterns! For now, though, just know that extracting data from structures such as our tuple is very easy with patterns. Take a look:
To be clear: had we needed to do this in a function, we would have used
Now we can references our data by the variables we bound when we extracted it
with the pattern in our