字典
字典
我们将一组键惟一的键—值(Key-Value)对定义为字典[3]。存在字典里的值可能会重复。对Key和Value的数据类型都没有限制,但是只能通过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
-module(dictionary).
-export([new/0,lookup/2,add/3,delete/2]).
new() ->
[].
lookup(Key, [{Key,Value}|Rest]) ->
{value,Value};
lookup(Key, [Pair|Rest]) ->
lookup(Key, Rest);
lookup(Key, []) ->
undefined.
add(Key, Value, Dict) ->
NewDict = delete(Key, Dict),
[{Key,Value}|NewDict].
delete(Key, [{Key,Value}|Rest]) ->
Rest;
delete(Key, [Pair|Rest]) ->
[Pair|delete(Key, Rest)];
delete(Key, []) ->
[].
我们用字典来构建和管理一个包含了各位作者鞋码的小型数据库:
D0 = dictionary:new().
[]
> D1 = dictionary:add(joe, 42, D0).
[{joe,42}]
> D2 = dictionary:add(mike, 41, D1).
[{mike,41},{joe,42}]
> D3 = dictionary:add(robert, 43, D2).
[{robert,43},{mike,41},{joe,42}]
> dictionary:lookup(joe, D3).
{value,42}
> dictionary:lookup(helen, D3).
undefined
...
