1. 程式人生 > 實用技巧 >Erlang中的巨集定義應該在什麼時候用

Erlang中的巨集定義應該在什麼時候用

讀<Erlang OTP併發程式設計實戰>中看到這麼一句話,遂做筆記以記錄:

  巨集不是函式的替代品,當你所需的抽象無法用普通函式來實現時,巨集給出了一條生路,比如,必須確保在編譯期展開某些程式碼的時候,或是在語法不允許執行函式呼叫的時候.

對於後者做了測試如下: 

 1 -module(test).
 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