May 13, 2021 Erlang
Although metagroups can group data into groups, we also need to represent a list of data. T he list in Erlang is enclosed in square brackets. F or example, a list of temperatures in different cities around the world can be expressed as:
[{moscow, {c, -10}}, {cape_town, {f, 70}}, {stockholm, {c, -4}},
{paris, {f, 28}}, {london, {f, 36}}]
Note that this list is too long to be placed on a row, but it doesn't matter. E rlang allows line changes in "reasonable places", but not in the middle of "unreasonable parties", such as atomic types, integers, or other data types.
You can use | to view a list of sections. T his usage will be explained in the following example:
17> [First |TheRest] = [1,2,3,4,5].
[1,2,3,4,5]
18> First.
1
19> TheRest.
[2,3,4,5]
You can use | S plit the first element in the list from the other elements in the list. T he First value is 1, and TheRest's value is 2, 3, 4, 5.
Next example:
20> [E1, E2 | R] = [1,2,3,4,5,6,7].
[1,2,3,4,5,6,7]
21> E1.
1
22> E2.
2
23> R.
[3,4,5,6,7]
In this example, we use | T he first two elements in the list were obtained. I f the number of elements you want to get exceeds the total number of elements in the list, an error is returned. N ote the special case in the list, the empty list (without elements), i.e., the
24> [A, B | C] = [1, 2].
[1,2]
25> A.
1
26> B.
2
27> C.
[]
In the previous example, we used a new variable name without reusing an existing variable name: First, TheRest, E1, R, A, B, or C. T his is because a variable can only be assigned once in the same context. We'll cover it in more detail later.
The following example shows how to get the length of a list. S ave the following code in file tut4.erl:
-module(tut4).
-export([list_length/1]).
list_length([]) ->
0;
list_length([First | Rest]) ->
1 + list_length(Rest).
Compile and run:
28> c(tut4).
{ok,tut4}
29> tut4:list_length([1,2,3,4,5,6,7]).
7
The code means something like this:
list_length([]) ->
0;
The length of the empty list is obviously 0.
list_length([First | Rest]) ->
1 + list_length(Rest).
A list contains the first element First with the remaining element list Rest, so the list length is rest list length plus 1.
(Advanced topic: This is not tail recursion, and there are ways to better implement this function.) )
In general, the metagroup type in Erlang assumes the function of recording or structure type in other languages. A list is a variable long container that has the same list functionality as in other languages.
There are no string types in Erlang. B ecause strings in Erlang can be represented by a list of Unicode characters. T his also implies that the list is equivalent to the string "abc". E rlang's shell is very "smart" and can guess what the list represents to output it in the most appropriate way, such as:
30> [97,98,99]
"abc"