编写Erlang程序的时候,最令人难以适应的就是“变量不能二次赋值”这条规定,幸好Erlang提供了Process Dictionary (进程字典?下面简称PD)这种机制,PD系Erlang中每个进程所私有的一个数据列表,存储有{变量名,变量值}这样的数据,并提供了如下BIFs来 操作PD:
@spec put(Key, Value) -> OldValue.
Add a Key, Value association to the process dictionary. The value of put is OldValue, which is the previous value associated with Key. If there was no previous value, the atom undefined is returned.
@spec get(Key) -> Value.
Look up the value of Key. If there is an association Key, Value association in the dictionary, return Value; otherwise, return the atom undefined
@spec get() -> [{Key,Value}].
Return the entire dictionary as a list of {Key,Value} tuples.
@spec get_keys(Value) -> [Key].
Return a list of keys that have the values Value in the dictionary.
@spec erase(Key) -> Value.
Return the value associated with Key or the atom undefined if there is no value associated with Key. Finally, erase the value associated with Key.
@spec erase() -> [{Key,Value}].
Erase the entire process dictionary. The return value is a list of {Key,Value} tuples representing the state of the dictionary before it was erased.
懒,不想翻译了,反正上面的英文那么浅,大家自己看看吧,下面是几个例子:
1> erase().
[]
2> put(x, 20).
undefined
3> get(x).
20
4> get(y).
undefined
5> put(y, 40).
undefined
6> get(y).
40
7> get().
[{y,40},{x,20}]
8> erase(x).
20
9> get().
[{y,40}]
大家可以看到,PD的用法就像是我们所认识的“正常的变量”一样可以二次赋值,但照《Programming Erlang》作者的说法,他是十分不赞同滥用PD的,原因是违背了Erlang变量不能二次赋值的原则,而且容易产生难以察觉的BUG~~
0 意見