> Erlang中文手册 > take_smallest/1 从树里提取最小的元素

gb_trees:take_smallest/1

从树里提取最小的元素

用法:

take_smallest(Tree1) -> {Key, Val, Tree2}

内部实现:

-spec take_smallest(Tree1) -> {Key, Val, Tree2} when
      Tree1 :: gb_tree(),
      Tree2 :: gb_tree(),
      Key :: term(),
      Val :: term().

take_smallest({Size, Tree}) when is_integer(Size), Size >= 0 ->
    {Key, Value, Larger} = take_smallest1(Tree),
    {Key, Value, {Size - 1, Larger}}.

take_smallest1({Key, Value, nil, Larger}) ->
    {Key, Value, Larger};
take_smallest1({Key, Value, Smaller, Larger}) ->
    {Key1, Value1, Smaller1} = take_smallest1(Smaller),
    {Key1, Value1, {Key, Value, Smaller1, Larger}}.

返回一个 {Key, Val, Tree2} 的元组,Key 是树 Tree1 里最小的键,Val 是跟键 Key 相关联的值,Tree2 是删去该键相应节点后的树(这里假设该树不是一个空树)。

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