> Erlang中文手册 > update/3 更新树里键的值

gb_trees:update/3

更新树里键的值

用法:

update(Key, Val, Tree1) -> Tree2

内部实现:

-spec update(Key, Val, Tree1) -> Tree2 when
      Key :: term(),
      Val :: term(),
      Tree1 :: gb_tree(),
      Tree2 :: gb_tree().

update(Key, Val, {S, T}) ->
    T1 = update_1(Key, Val, T),
    {S, T1}.

%% See 'lookup' for notes on the term comparison order.

update_1(Key, Value, {Key1, V, Smaller, Bigger}) when Key  
    {Key1, V, update_1(Key, Value, Smaller), Bigger};
update_1(Key, Value, {Key1, V, Smaller, Bigger}) when Key > Key1 ->
    {Key1, V, Smaller, update_1(Key, Value, Bigger)};
update_1(Key, Value, {_, _, Smaller, Bigger}) ->
    {Key, Value, Smaller, Bigger}.

把树 Tree1 里键 Key 的值更为 Val,最后返回一个新树 Tree2(这里假设该键在树里存在)。

Orddict = orddict:from_list([{pear, 7}, {orange, 5}, {apple, 2}]),
Tree = gb_trees:from_orddict(Orddict),
gb_trees:update(apple, 10, Tree).