erlang的函数

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诡异的语法,觉得这个是不是很容易理解了。

猜你喜欢

转载自somefuture.iteye.com/blog/2196195