erlang编程指南 练习3-4
练习3-4??? 编写创建一个数据库模块db.erl,它能够模拟数据库 存储,检索和删除元素。
提示使用列表和元组作为你的主要数据结构,当测试程序时,请记住Erlang中变量是单次赋值。
接口:
db:new()?????? =>Db.
db:destroy(Db)???? =>ok.
db:write(Key,Element,Db)? =>newDb.
db:read(Key,Db)? =>{ok,Element}|{error,instance}.
db:match(Element,Db) =>[key1,.......,keyN].
?
代码如下:
?
%% Author: liu.guangjun%% Created: 2011-12-5%% Description: TODO: Add description to db-module(db).%%%% Include files%%%%%% Exported Functions%%-export([new/0,write/3,delete/2,read/2,match/2]).% -export([destroy/1]).%%%% Local Functions%%new()->[].%destroy(Db)-> f(Db).write(Key,Element,Db)->[{Key,Element}|Db]. %% read(Key,Db)->%% case lists:keyfind(Key, 1, Db) of%% {_,Element} ->{ok,Element};%% false->{error,instance}%% end.read(_,[])->{error,instance};read(Key,[H1|T1])-> case H1 of {Key,Element} ->{ok,Element};_ -> read(Key,T1) end.delete(Key,Db)->delete_element(Key,Db,[]).delete_element(_,[],List2)->List2;delete_element(Key,[H1|T1],T2)->case H1 of{Key,_} -> delete_element(Key,T1,T2); _->delete_element(Key,T1,[H1|T2]) end.match(Element,Keys)->match_element(Element,Keys,[]).match_element(_,[],Keys)->Keys;match_element(Element,[H|T],T2)->case H of{H2,Element} ->match_element(Element,T,[H2|T2]);_->match_element(Element,T,T2)end.
?
?
?
?
?