开发者

Newbie's question for Erlang dict

开发者 https://www.devze.com 2023-01-16 03:37 出处:网络
I\'m reading Programming Erlang by Joe Armstrong(Pragmatic Bookshelf). In name_server.erl source code on Chapter 16, Where\'s Dict variable from? Calling dict:new() generates Dict automatically? And,

I'm reading Programming Erlang by Joe Armstrong(Pragmatic Bookshelf). In name_server.erl source code on Chapter 16, Where's Dict variable from? Calling dict:new() generates Dict automatically? And, reference says that dict:new() creates dictionary. Don't 开发者_如何学编程I need to store it as a variable like Dict = dict:new()?

-module(name_server).
-export([init/0, add/2, whereis/1, handle/2]).
-import(server1, [rpc/2]).

add(Name, Place)  ->
  rpc(name_server, {add, Name, Place}).

whereis(Name) ->
  rpc(name_server, {whereis, Name}).

init()  ->
  dict:new().

handle({add, Name, Place}, Dict)  ->
  {ok, dict:store(Name, Place, Dict)};
handle({whereis, Name}, Dict) ->
  {dict:find(Name, Dict), Dict}.


This is part of a two file example. The other file (immediately before it in the book) is server.erl. It contains a loop function that calls the handle function in name_server.erl (or whatever module you pass to it):

The line is:

{Response, State1} = Mod:handle(Request, State),

where Mod is the module passed to start earlier. And State is initialised earlier as Mod:init() in the start function.

So State is initialised to name_server:init() which in your file returns dict:new(). However, as loop is called recursively State will take the next value of State1.

So when handle is called, Dict is set to the current value of State.

0

精彩评论

暂无评论...
验证码 换一张
取 消