[erlang-questions] need some help with erlang

wde <>
Tue Feb 16 19:42:14 CET 2010


a simple example :

-module(db_server).

-export([start/0, init/1, write/2, read/1]).

start() ->
    register(server, spawn(db_server, init, [dict:new()])).

init(Records) ->
    receive
        {From,{add, Key, Value}} ->
            NewRecords = dict:store(Key, Value, Records),
            From ! {self(),{ok, Key, Value}},
	   init(NewRecords);
        {From,{show, Key} }->
            Resp =
			case dict:find(Key, Records) of
		                {ok, Value} -> Value;
		                error -> {error, no_such_value}
		         end,
	   From ! {self(),Resp},
	   init(Records);
        {From,{delete, Key}} ->
            NewRecords = dict:erase(Key, Records),
            From ! {self(),ok},
	   init(NewRecords)
    end.


write(Key, Value) ->
	server ! {self(),{add, Key, Value}},
	receive
		{_From,Msg} -> Msg
	after 2000 ->
		ok
	end.

read(Key) ->
    server ! {self(),{show, Key}},
	receive
		{_From,Msg} -> Msg
	after 2000 ->
		ok
	end.



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




More information about the erlang-questions mailing list