erlang的方法申明是其引以爲豪的,雖然被不用erlang的人嘲笑。
巨醜無比是吧。
erlang聲稱自己的函數調用使用的是Pattern Match模式匹配:
function(Args)
if X then
Expression
else if Y then
Expression
else
Expression
這是其他語言的風格,erlang把上面的一個方法拆開成好幾個function聲明:
function(X) -> Expression; function(Y) -> Expression; function(_) -> Expression.
不過注意,實際上他們是一個整體*(函數名稱也是一致的),因爲只有到最後採用了結束的點號,中間都用的分號。
比如:
greet(male, Name) -> io:format("Hello, Mr. ~s!", [Name]); greet(female, Name) -> io:format("Hello, Mrs. ~s!", [Name]); greet(_, Name) -> io:format("Hello, ~s!", [Name]).
再比如判斷年齡是否正常的方法:
right_age(X) when X >= 16, X =< 104 ->
true;
right_age(_) ->
false.
裏面的逗號意思是andalso,而分號意思實際上是orelse:所以它的反函數不再使用逗號
wrong_age(X) when X < 16; X > 104 -> true; wrong_age(_) -> false.
這一點是尤其要注意的。
接下來是erlang裏面的if/else。 erlang沒有else 關鍵字。
help_me(Animal) -> Talk = if Animal == cat -> "meow"; Animal == beef -> "mooo"; Animal == dog -> "bark"; Animal == tree -> "bark"; true -> "fgdadfgna" end, {Animal, "says " ++ Talk ++ "!"}.
把幾個elseif並列起來用分號隔開就行,而else則直接寫爲true,因爲上面的比較返回的false,這裏遇見true就可以是剩下的全部情況了。
另外一種分支流程判斷是case of:
beach(Temperature) -> case Temperature of {celsius, N} when N >= 20, N =< 45 -> 'favorable'; {kelvin, N} when N >= 293, N =< 318 -> 'scientifically favorable'; {fahrenheit, N} when N >= 68, N =< 113 -> 'favorable in the US'; _ -> 'avoid beach' end.
看慣了erlang詭異的語法,覺得這個是不是很容易理解了。