Erlang基础 - 函数、子句、子句保护式

来源:互联网 发布:淘宝客服哪里培训课程 编辑:程序博客网 时间:2024/06/05 04:53
这个标题的内容就简单多了,直接看用例吧,仍然以 helloworld.erl模块为例。
函数:
%% This is a simple Erlang module%  Test ...-module(helloworld).-export([pie/0, print/1]).pie() ->        3.14        .print(Msg) ->        io:format("The Message is ~p.~n",[Msg])  %~p 表示以美化的方式打印Erlang项式,~n 表示插入一个换行符, ~w 表示打印Erlang字符串

函数子句:

-module(helloworld).-export([area/1, either_or_both/2]).% “_” 表示省略模式either_or_both(true, _) ->        true;either_or_both(_, true) ->        false;either_or_both(false, false) ->        false;area({a, X, Y}) ->         io:format("a, X, Y: ~p, ~p, ~p.~n", [a, X, Y]); area({b, X, Y}) ->         io:format("b, X, Y: ~p, ~p, ~p.~n", [b, X, Y]). %编译:c(helloworld).%调用函数:1> helloworld:area({a, 500, 500}).a, X, Y: a, 500, 500.ok2> 
注意:子句是用分好分隔且最后一个子句由句号结尾。同意函数的所有子句必须具备相同的函数名和相同的参数数量,且必须在同一处定义,不允许在同一函数的两个子句之间再插入其他函数定义。

对于either_or_both函数,如果传递的参数为either_or_both(true, 42),很显然是成立的,它只会平静地返回true,因此这就需要用到我们的保护式。


子句保护式:

-module(helloworld).-export([either_or_both/2]).either_or_both(true, B) when is_boolean(B) ->        true;either_or_both(A, true) when is _boolean(A) ->        false;either_or_both(false, false) ->        false;

子句保护式由关键字when开始到->符号结束。能用在保护式中得操作时十分有限的,大部分运算符都可以使用(+、-、*、/、++等),部分内置函数也可以用,如:self()、 is_boolean(...)、is_integer(...)、is_atom(...)等,但你不能调用自定义的函数或其他模块中得函数。


0 0
原创粉丝点击