读<Erlang OTP并发编程实战>中看到这么一句话,遂做笔记以记录:
宏不是函数的替代品,当你所需的抽象无法用普通函数来实现时,宏给出了一条生路,比如,必须确保在编译期展开某些代码的时候,或是在语法不允许执行函数调用的时候.
对于后者做了测试如下:
1 -module(test_macro). 2 -export([test/2]). 3 test(X, Y) -> 4 if 5 maxxx(X, Y) -> 6 X; 7 true -> 8 Y 9 end. 10 maxxx(X, Y) -> 11 X > Y.
此时编译会报错如下:
3>c(test_macro). test_macro.erl:5: call to local/imported function maxxx/2 is illegal in guard test_macro.erl:10: Warning: function maxxx/2 is unused error
此时尝试使用宏定义来解决,修改代码如下:
1 -module(test_macro). 2 -export([test/2]). 3 -define(maxxx(X, Y), X > Y). 4 test(X, Y) -> 5 if 6 ?maxxx(X, Y) -> 7 X; 8 true -> 9 Y 10 end.
编译:
1 4> c(test_macro). 2 {ok,test_macro}
顺利编译完成:调用测试用例:
5>test_macro:test(1,2). 2 6> test_macro:test(3,5). 5 7> test_macro:test(10,5). 10 8> test_macro:test(10,-5). 10 9> test_macro:test(-10,5). 5
浙公网安备 33010602011771号