Content deleted Content added
→Delphi: +Erlang |
|||
Line 244:
end;
</source>
===Erlang===
Erlang offers many approaches to represent mappings, two of the most common in the standard library are keylists and dictionaries.
Keylists are lists of tuples, where the first element of each tuple is a key, and the second is a value. Functions for operating on keylists are provided in the <code>lists</code> module.
<source lang="erlang">
PhoneBook = [{"Sally Smart", "555-9999"},
{"John Doe", "555-1212"},
{"J. Random Hacker", "553-1337"}].
</source>
Accessing an element of the keylist can be done with the <code>lists:keyfind/3</code> function:
<source lang="erlang">
{_, Phone} = lists:keyfind("Sally Smart", 1, PhoneBook),
io:format("Phone number: ~s~n", [Phone]).
</source>
Dictionaries are implemented in the <code>dict</code> of the standard library. A new dictionary is created using the <code>dict:new/0</code> function and new key/value pairs are stored using the <code>dict:store/3</code> function:
<source lang="erlang">
PhoneBook1 = dict:new(),
PhoneBook2 = dict:store("Sally Smith", "555-9999", Dict1),
PhoneBook3 = dict:store("John Doe", "555-1212", Dict2),
PhoneBook = dict:store("J. Random Hacker", "553-1337", Dict3).
</source>
Such a serial initialization would be more idiomatically represented in Erlang with the appropriate function:
<source lang="erlang">
PhoneBook = dict:from_list([{"Sally Smith", "555-9999"}, {"John Doe", "555-1212"},
{"J. Random Hacker", "553-1337"}]).
</source>
The dictionary can be accessed using the <code>dict:find/2</code> function:
<source lang="erlang">
{ok, Phone} = dict:find("Sally Smith", PhoneBook),
io:format("Phone: ~s~n", [Phone]).
</source>
In both cases, any Erlang term can be used as the key. Variations include the <code>orddict</code> module, implementing ordered dictionaries, and <code>gb_trees</code>, implementing general balanced trees.
=== FoxPro ===
|