Erlang中文手册(Erldoc.com)  »  gb_trees  »  lookup/2
Erlang并发编程 Erlang/OTP设计原理 Erlang/OTP[pdf] Mnesia用户手册[pdf] Erlang完整手册[en] 官网手册[en] 模块列表 方法列表 随机 Erlang中文社区(BBS) 美女图库

gb_trees:lookup/2

在树里查找一个值

用法:

lookup(Key, Tree) -> none | {value, Val}

内部实现:

-spec lookup(Key, Tree) -> 'none' | {'value', Val} when
      Key :: term(),
      Val :: term(),
      Tree :: gb_tree().

lookup(Key, {_, T}) ->
    lookup_1(Key, T).

%% The term order is an arithmetic total order, so we should not
%% test exact equality for the keys. (If we do, then it becomes
%% possible that neither '>', '<', nor '=:=' matches.) Testing '<'
%% and '>' first is statistically better than testing for
%% equality, and also allows us to skip the test completely in the
%% remaining case.

lookup_1(Key, {Key1, _, Smaller, _}) when Key < Key1 ->
    lookup_1(Key, Smaller);
lookup_1(Key, {Key1, _, _, Bigger}) when Key > Key1 ->
    lookup_1(Key, Bigger);
lookup_1(_, {_, Value, _, _}) ->
    {value, Value};
lookup_1(_, nil) ->
    none.

在树里查找一个跟键 Key 相关的值,如果存在,则返回 {value, Val},否则返回 none。

Tree1 = gb_trees:empty(),
Tree2 = gb_trees:enter(a, 1, Tree1),
gb_trees:lookup(a, Tree2).
Tree1 = gb_trees:empty(),
gb_trees:lookup(a, Tree1).
阿里云 - 最高1000元通用代金券立即可用
沪ICP备13037221号-9