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

Продолжу публиковать свои варианты решений задач из «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:

Interface:

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].

Example:

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

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

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

new() ->
  [].

destroy(_) ->
  new().

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

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

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).

Comments

comments


Bookmark and Share