Archive for the ‘erlang’ tag
How erlang RECEIVE works
receive works as follows:
-
When we enter a receive statement, we start a timer (but only if an after section is present in the expression).
-
Take the first message in the mailbox and try to match it against Pattern1, Pattern2, and so on. If the match succeeds, the message is removed from the mailbox, and the expressions following the pattern are evaluated.
-
If none of the patterns in the receive statement matches the first message in the mailbox, then the first message is removed from the mailbox and put into a “save queue.” The second message in the mailbox is then tried. This procedure is repeated until a matching message is found or until all the messages in the mailbox have been examined.
-
If none of the messages in the mailbox matches, then the process is suspended and will be rescheduled for execution the next time a new message is put in the mailbox. Note that when a new message arrives, the messages in the save queue are not rematched; only the new message is matched.
-
As soon as a message has been matched, then all messages that have been put into the save queue are reentered into the mailbox in the order in which they arrived at the process. If a timer was set, it is cleared.
-
If the timer elapses when we are waiting for a message, then evaluate the expressions ExpressionsTimeout and put any saved messages back into the mailbox in the order in which they arrived at the process.
Erlang tips
% setting search paths for loading code
@spec code:add_patha(Dir) => true | {error, bad_directory}
@spec code:add_pathz(Dir) => true | {error, bad_directory}
% examine loaded code
code:all_loaded()
code:clash()
% start a server to view error log friendly
webtool:start().
Erlang中的fun关键字
fun首先可以用来定义匿名函数(Erlang中称为funs)。
1> Z = fun(X) -> 2 * X end. 2> Hypot = fun(X,Y) -> math:sqrt(X*X+Y*Y) end. %% 调用方法 3> Z(2). ... 4> Hypot(3,4).
fun也可以用来引用函数。
本模块内引用:
fun LocalFunc/Arity
引用其他模块的函数:
fun Mod:RemoteFunc/Arity
具体例子:
-module(x1). -compile(export_all). square(X) -> X * X. ... double(L) -> lists:map(fun square/1, L).
-module(x2). -compile(export_all). ... double(L) -> lists:map(fun x1:square/1, L).
其实我还是比较认同fun只有一个函数引用的功能,定义匿名函数的时候,fun是对一个匿名函数进行了引用。
Quick Sort in Erlang
qsort([]) ->
[];
qsort([Pivot|T]) ->
qsort([X || X <- T, X < Pivot])
++Pivot++
qsort([X || X <- T, X >= Pivot]).
用到了list comprehension,很好的功能。