[erlang-questions] need some help with erlang
Doug Fort
doug.fort@REDACTED
Tue Feb 16 19:43:42 CET 2010
On Tue, Feb 16, 2010 at 1:13 PM, Sarvar Muminov
<sarvar.muminov@REDACTED> wrote:
> I wrote this small db emulator to store the data in a hash.
> I used "write" function to write data to the hash. But when I try to add
> some data with key, value, It didn't work.
> I suppose I made some mistake in the code, but I can't figure out the
> problem :)
>
> -module(db_server).
>
> -export([start/0, init/1, write/2, read/1]).
>
> start() ->
> register(server, spawn(db_server, init, [dict:new()])).
>
> init(Records) ->
> receive
> {add, Key, Value} ->
> dict:store(Key, Value, Records),
> {ok, Key, Value};
> {show, Key} ->
> case dict:find(Key, Records) of
> {ok, Value} -> Value;
> error -> {error, no_such_value}
> end;
> {delete, Key} ->
> dict:erase(Key, Records),
> ok
> end,
> init(Records).
>
> write(Key, Value) ->
> server ! {add, Key, Value}.
>
> read(Key) ->
> server ! {show, Key}.
>
Hi Sarvar,
You are discovering a key point of functional programming.
Immutability. dict:new() does not create an object as java or python
would. It creates an immutable data structure. When you call
dict:store(Key, Value, Records), the return value is a new instance of
the data structure. The data structure 'Records' has not been changed.
So you need to do something like Records1 = dict:store(Key, Value,
Records), and then pass Records1 to init on you next loop.
--
Doug Fort, Consulting Programmer
http://www.dougfort.com
More information about the erlang-questions
mailing list