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/2equal?/2fetch!/2get/2get/3has_key?/2keys/1merge/2merge/3pop/2pop/3put_new/3split/2take/2to_list/1update/4update!/3values/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