新手关于 Erlang dict 的问题
我正在阅读 Joe Armstrong 的《Programming Erlang》(实用书架)。在第16章的name_server.erl源代码中,Dict变量来自哪里?调用 dict:new() 自动生成 Dict?并且,参考文献说 dict:new() 创建字典。我不需要将其存储为像 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}.
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}.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是两个文件示例的一部分。另一个文件(在本书中就在它之前)是
server.erl
。它包含一个loop
函数,该函数调用name_server.erl
(或您传递给它的任何模块)中的handle
函数:该行是
:
Mod
是之前传递给start
的模块。并且State
在 start 函数中被初始化为Mod:init()
。因此,
State
被初始化为name_server:init()
,它在您的文件中返回dict:new()
。但是,当递归调用loop
时,State
将采用State1
的下一个值。因此,当调用
handle
时,Dict
将设置为State
的当前值。This is part of a two file example. The other file (immediately before it in the book) is
server.erl
. It contains aloop
function that calls thehandle
function inname_server.erl
(or whatever module you pass to it):The line is:
where
Mod
is the module passed tostart
earlier. AndState
is initialised earlier asMod:init()
in the start function.So
State
is initialised toname_server:init()
which in your file returnsdict:new()
. However, asloop
is called recursivelyState
will take the next value ofState1
.So when
handle
is called,Dict
is set to the current value ofState
.