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:


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

Site Footer

Sliding Sidebar

About Me

About Me

For whom this blog for?

For those who are interested in modern Internet technologies, IT business, startups, management, quality control, personal effectiveness, motivation. Here I write about what is interesting, about problems I faced and solutions I found. I hope it will be interesting to you either.

What motivates me to write?

The desire to improve, to study deeper topics that interest me. Find people with similar problems and tasks, together look for ways out and solutions.

Feel free to contact if you have anything to say to me

Old Flash site with my artistic works and misuc.