• 字典

    字典

    我们将一组键惟一的键—值Key-Value)对定义为字典[3]。存在字典里的值可能会重复。对KeyValue的数据类型都没有限制,但是只能通过Key来查询字典。

    我们定义一下字典操作:

    new()
    创建并返回一个空字典。
    lookup(Key,Dict)
    在字典Dict中查找一个Key-Value对,如果找到则返回{value, Value},否则返回undefined
    add(Key,Value,Dict)
    添加一个新的Key-Value对到字典Dict中,并返回一个新的字典,以反映add函数对字典造成的改变。
    delete(Key,Dict)
    从字典Dict里删除Key所对应的Key-Value对,并返回一个新的字典。

    程序4.1展示了一个字典是怎样将Key-Value对以元组的形式存放到列表里面的。它并不是实现一个字典最好的方法,在这里它只是一个例子。

    程序4.1

    1. -module(dictionary).
    2. -export([new/0,lookup/2,add/3,delete/2]).
    3.  
    4. new() ->
    5. [].
    6.  
    7. lookup(Key, [{Key,Value}|Rest]) ->
    8. {value,Value};
    9.  
    10. lookup(Key, [Pair|Rest]) ->
    11. lookup(Key, Rest);
    12.  
    13. lookup(Key, []) ->
    14. undefined.
    15.  
    16. add(Key, Value, Dict) ->
    17. NewDict = delete(Key, Dict),
    18. [{Key,Value}|NewDict].
    19.  
    20. delete(Key, [{Key,Value}|Rest]) ->
    21. Rest;
    22.  
    23. delete(Key, [Pair|Rest]) ->
    24. [Pair|delete(Key, Rest)];
    25. delete(Key, []) ->
    26. [].

    我们用字典来构建和管理一个包含了各位作者鞋码的小型数据库:

    1. D0 = dictionary:new().
    2. []
    3. > D1 = dictionary:add(joe, 42, D0).
    4. [{joe,42}]
    5. > D2 = dictionary:add(mike, 41, D1).
    6. [{mike,41},{joe,42}]
    7. > D3 = dictionary:add(robert, 43, D2).
    8. [{robert,43},{mike,41},{joe,42}]
    9. > dictionary:lookup(joe, D3).
    10. {value,42}
    11. > dictionary:lookup(helen, D3).
    12. undefined
    13. ...