Radix.get_and_update

You're seeing just the function get_and_update, go back to Radix module for more information.
Link to this function

get_and_update(tree, key, fun)

View Source

Specs

get_and_update(
  tree(),
  key(),
  (nil | {key(), value()} -> {value(), value()} | :pop)
) ::
  {value(), tree()}

Updates a key,value-pair in tree by invoking fun with the result of an exact match.

The callback fun is called with:

  • {key, original_value} if an exact match was found, or
  • nil, in case the key is not present in tree

The callback function should return:

  • {current_value, new_value}, or
  • :pop.

When {current_value, new_value} is returned, the new_value is stored under key and {current_value, tree} is returned. When the callback passes back :pop, the {key, original_value}-pair is deleted from the tree and {original_value, tree} is returned.

If the callback passes back :pop when its argument was nil then {nil, tree} is returned, where tree is unchanged.

If something similar is required, but based on a longest prefix match, perhaps Radix.update/3 or Radix.update/4 is better suited.

Examples

# update stats, get org value and store new value
iex> count = fn nil -> {0, 1}; {_key, val} -> {val, val+1} end
iex> t = new([{<<1,1,1>>, 1}, {<<2, 2, 2>>, 2}])
iex> {org, t} = get_and_update(t, <<1, 1, 1>>, count)
iex> org
1
iex> get(t, <<1, 1, 1>>)
{<<1, 1, 1>>, 2}
iex> {org, t} = get_and_update(t, <<3, 3>>, count)
iex> org
0
iex> get(t, <<3, 3>>)
{<<3, 3>>, 1}

# modify `count` callback so we get the new value back + updated tree
iex> count = fn nil -> {1, 1}; {_key, val} -> {val+1, val+1} end
iex> t = new([{<<1,1,1>>, 1}, {<<2, 2, 2>>, 2}])
iex> {new, t} = get_and_update(t, <<1, 1, 1>>, count)
iex> new
2
iex> get(t, <<1, 1, 1>>)
{<<1, 1, 1>>, 2}
iex> {new, t} = get_and_update(t, <<3, 3>>, count)
iex> new
1
iex> get(t, <<3, 3>>)
{<<3, 3>>, 1}

# returning :pop deletes the key
iex> once = fn nil -> {0, 1}; {_k, _v} -> :pop end
iex> t = new([{<<1, 1>>, 1}])
iex> {val, t} = get_and_update(t, <<2, 2>>, once)
iex> val
0
iex> get(t, <<2, 2>>)
{<<2, 2>>, 1}
iex> {val, t} = get_and_update(t, <<1, 1>>, once)
iex> val
1
iex> get(t, <<1, 1>>)
nil