Erlang. Упражнения (продолжение).

Database Handling Using Lists

Продолжу публиковать свои варианты решений задач из «Erlang programming» Франческо Чезарини и Саймона Томпсона.

Exercise 3-4: Database Handling Using Lists

Write a module db.erlthat creates a database and is able to store, retrieve, and delete
elements in it. The destroy/1function will delete the database. Considering that Erlang
has garbage collection, you do not need to do anything. Had the dbmodule stored
everything on file, however, you would delete the file. We are including the destroy
function to make the interface consistent. You may notuse the listslibrary module,
and you have to implement all the recursive functions yourself.

Hint: use lists and tuples as your main data structures. When testing your program,
remember that Erlang variables are single-assignment:


db:new()  ⇒ Db.
db:destroy(Db)  ⇒ ok.
db:write(Key, Element, Db)  ⇒ NewDb.
db:delete(Key, Db)  ⇒ NewDb.
db:read(Key, Db)  ⇒{ok, Element} | {error, instance}.
db:match(Element, Db)  ⇒ [Key1, ..., KeyN].


1> c(db).
2>  Db = db:new().
3>  Db1 = db:write(francesco, london, Db).
4> Db2 = db:write(lelle, stockholm, Db1).
5> db:read(francesco, Db2).
6>  Db3 = db:write(joern, stockholm, Db2).
7>  db:read(ola, Db3).
8>  db:match(stockholm, Db3).
9>  Db4 = db:delete(lelle, Db3).
10> db:match(stockholm, Db4).

И мой вариант решения:

-module (test3_4).
-import (io).

new() ->

destroy(_) ->

write(Key, Element, Db) ->
  Db ++ [{Key, Element}].

filter(_, [], Result) ->
filter(F, [Head | Tail], Result) ->  
    F(Head) of true ->
      filter(F, Tail, Result ++ [Head]);
    false -> 
      filter(F, Tail, Result)

remove(Key, Db) ->
  filter(fun(X) -> element(1, X) /= Key end, Db, []).

read(Key, Db) ->
  filter(fun(X) -> element(1, X) == Key end, Db, []).

match(Value, Db) -> 
  [Result | _ ] = filter(fun(X) -> element(2, X) == Value end, Db, []),  
  element(1, Result).

test() -> 
  Db = write(key2, value2, write(key1, value1, new())),
  match(value1, Db).



One thought on “Erlang. Упражнения (продолжение).”

  1. Мой вариант:





    write(Key, Element, Db)->[{Key,Element}] ++ Db.

    read(Key, []) ->{error, instance};
    read(Key, [{Key,Element}|_])->{ok,Element};
    read(Key, [{_,_}|T])->read(Key,T).

    delete(Key,[H|T]) -> [H| delete(Key,T)].

    match(Element, [])->[];
    match(Element, [{Key,Element}|T])->[Key| match(Element,T)];
    match(Element, [{_,_}|T])->match(Element,T).

Leave a Reply