[erlang-questions] need some help with erlang

Dale Harvey dale@REDACTED
Tue Feb 16 19:39:47 CET 2010


a few things wrong with this

On 16 February 2010 18:13, 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} ->
>

When you compile you should get warning that a term is constructed and never
used,
you arent doing anything with it, you can io:format it out, typically you
would send the server
your own pid with self() so it can send the value back


>            case dict:find(Key, Records) of
>                {ok, Value} -> Value;
>                error -> {error, no_such_value}
>            end;
>        {delete, Key} ->
>            dict:erase(Key, Records),
>            ok
>    end,
>

You are calling the loop function with the same variable it as passed in,
which was dict:new(), so it will
always be a new (empty) dict, when you modify the dict you need to call it
with the new version


>    init(Records).
>
> write(Key, Value) ->
>    server ! {add, Key, Value}.
>
> read(Key) ->
>    server ! {show, Key}.
>


More information about the erlang-questions mailing list