Elixir v1.1.1 Access behaviour

Dictionary-like access to data structures via the foo[bar] syntax.

This module also empowers Kernels nested update functions Kernel.get_in/2, Kernel.put_in/3, Kernel.update_in/3 and Kernel.get_and_update_in/3.

Examples

Out of the box, Access works with built-in dictionaries: Keyword and Map:

iex> keywords = [a: 1, b: 2]
iex> keywords[:a]
1

iex> map = %{a: 1, b: 2}
iex> map[:a]
1

iex> star_ratings = %{1.0 => "★", 1.5 => "★☆", 2.0 => "★★"}
iex> star_ratings[1.5]
"★☆"

Furthermore, Access transparently ignores nil values:

iex> keywords = [a: 1, b: 2]
iex> keywords[:c][:unknown]
nil

The key comparison must be implemented using the === operator.

Summary

Functions

Fetches the container’s value for the given key

Gets the container’s value for the given key

Gets and updates the container’s value for the given key, in a single pass

Types

key :: any
t :: list | map | nil
value :: any

Functions

fetch(container, key)

Specs

fetch(t, term) :: {:ok, term} | :error

Fetches the container’s value for the given key.

get(container, key, default \\ nil)

Specs

get(t, term, term) :: term

Gets the container’s value for the given key.

get_and_update(container, key, fun)

Specs

get_and_update(t, term, (term -> {get, term})) :: {get, t} when get: var

Gets and updates the container’s value for the given key, in a single pass.

The argument function fun must receive the value for the given key (or nil if the key doesn’t exist in container). It must return a tuple containing the get value and the new value to be stored in the container.

This function returns a two-element tuple. The first element is the get value, as returned by fun. The second element is the container, updated with the value returned by fun.

Callbacks

fetch(t, key)

Specs

fetch(t, key) :: {:ok, value} | :error
get_and_update(t, key, list)

Specs

get_and_update(t, key, (value -> {value, value})) :: {value, t}