递归匿名函数等待某个消息(recursive anonymous functions and w
查看原文:http://www.wagerlabs.com/blog/2008/08/erlang-recursive-anonymous-functions-and-waiting-for-messages.html我们有个需求,我们要等待某个消息,同时过滤指定的消息。我们可以定义一个macro,来实现。
看代码:
-define(WAITMSG(Msg, Timeout, Skip), fun() -> F = fun(F) -> receiveMsg ->success;Packet ->DoSkip = lists:member(Packet, Skip),ifDoSkip ->F(F); true ->{error, Packet} endafter Timeout ->{error, timeout}endend, F(F)end()).
代码中需要说明的几个地方:
1,在macro中,我们定义了一个anonymous fun, 并执行(通过最后一行end()来调用),fun() -> some expression end() 即定义了一个fun,并调用。同样 fun(Arg1, Arg2..., ArgN) -> some expression end(Param1, Param2..., ParamN)也定义并调用了这个具有多个参数的anonymous fun.
2,F fun中,我们通过将anonymous函数作为参数传递的方法实现循环,即F(F).
使用这个macro
case ?WAITMSG(login, 1000, )of success -> io:format("success~n"); {error, Error} -> io:format("error~n")end
页:
[1]