`
litaocheng
  • 浏览: 333383 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

递归匿名函数等待某个消息(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) ->
			 receive
				Msg ->
					success;
				Packet ->
					DoSkip = lists:member(Packet, Skip),
					if
						DoSkip ->
							F(F);
					    true ->
							{error, Packet}
					 end
			after Timeout ->
				{error, timeout}
			end
		end,
        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, [msg1, msg2, msg3])  of
	    success ->
		    io:format("success~n");
	    {error, Error} ->
		    io:format("error~n")
end


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics