Content deleted Content added
DarthKitty (talk | contribs) →Erlang: use separate sections for keylists and dictionaries; add section on maps |
|||
Line 293:
===Erlang===
[[Erlang (programming language)|Erlang]] offers many ways to represent mappings;
====Keylists====
Keylists are lists of
<syntaxhighlight lang=Erlang>
PhoneBook = [{"Sally
{"John Doe", "555-1212"},
{"J. Random Hacker", "553-1337"}].
Line 306 ⟶ 307:
<syntaxhighlight lang=Erlang>
{_, Phone} = lists:keyfind("Sally
io:format("Phone number: ~s~n", [Phone]).
</syntaxhighlight>
====Dictionaries====
Dictionaries are implemented in the <code>dict</code> module 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:
<syntaxhighlight lang=Erlang>
Line 322 ⟶ 324:
<syntaxhighlight lang=Erlang>
PhoneBook = dict:from_list([{"Sally Smith", "555-9999"},
{"John Doe", "555-1212"}, {"J. Random Hacker", "553-1337"}]).
</syntaxhighlight>
Line 334 ⟶ 337:
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.
====Maps====
Maps were introduced in OTP 17.0,<ref>{{Cite web|title=Erlang -- maps|url=https://erlang.org/doc/man/maps.html|access-date=2021-03-07|website=erlang.org}}</ref> and combine the strengths of keylists and dictionaries. A map is defined using the syntax <code>#{ K1 => V1, ... Kn => Vn }</code>:
<syntaxhighlight lang=Erlang>
PhoneBook = #{"Sally Smith" => "555-9999",
"John Doe" => "555-1212",
"J. Random Hacker" => "553-1337"}.
</syntaxhighlight>
Basic functions to interact with maps are available from the <code>maps</code> module. For example, the <code>maps:find/2</code> function returns the value associated with a key:
<syntaxhighlight lang=Erlang>
{ok, Phone} = maps:find("Sally Smith", PhoneBook),
io:format("Phone: ~s~n", [Phone]).
</syntaxhighlight>
Unlike dictionaries, maps can be pattern matched upon:
<syntaxhighlight lang=Erlang>
#{"Sally Smith", Phone} = PhoneBook,
io:format("Phone: ~s~n", [Phone]).
</syntaxhighlight>
Erlang also provides syntax sugar for functional updates—creating a new map based on an existing one, but with modified values or additional keys:
<syntaxhighlight lang=Erlang>
PhoneBook2 = PhoneBook#{
% the `:=` operator updates the value associated with an existing key
"J. Random Hacker" := "355-7331",
% the `=>` operator adds a new key-value pair, potentially replacing an existing one
"Alice Wonderland" => "555-1865"
}
</syntaxhighlight>
===F#===
|