This module specifies the Dict API expected to be implemented by different dictionaries. It also provides functions that redirect to the underlying Dict, allowing a developer to work with different Dict implementations using one API.
To create a new dict, use the new
functions defined
by each dict type:
HashDict.new #=> creates an empty HashDict
In the examples below, dict_impl
means a specific
Dict
implementation, for example HashDict
or Map
.
Protocols
Besides implementing the functions in this module, all
dictionaries are required to implement the Access
protocol:
iex> dict = dict_impl.new
iex> dict = Dict.put(dict, :hello, :world)
iex> dict[:hello]
:world
As well as the Enumerable
and Collectable
protocols.
Match
Dictionaries are required to implement all operations
using the match (===
) operator.
Default implementation
Default implementations for some functions in the Dict
module
are provided via use Dict
.
For example:
defmodule MyDict do
use Dict
# implement required functions (see below)
# override default implementations if optimization
# is needed
end
The client module must contain the following functions:
All functions, except reduce/3
, are required by the Dict behaviour.
reduce/3
must be implemtented as per the Enumerable protocol.
Based on these functions, Dict
generates default implementations
for the following functions:
drop/2
equal?/2
fetch!/2
get/2
get/3
has_key?/2
keys/1
merge/2
merge/3
pop/2
pop/3
put_new/3
split/2
take/2
to_list/1
update/4
update!/3
values/1
All of these functions are defined as overridable, so you can provide your own implementation if needed.
Note you can also test your custom module via Dict
's doctests:
defmodule MyDict do
# ...
end
defmodule MyTests do
use ExUnit.Case
doctest Dict
defp dict_impl, do: MyDict
end