您的位置:首页 > 其它

Erlang笔记(05) - Erlang条件判断: if, case, when

2015-03-12 22:56 645 查看
1. if 语句

if 的格式,Action 执行的结果就是 if 语句的返回值

[plain] view
plaincopy





if

Condition 1 ->

Action 1;

Condition 2 ->

Action 2;

Condition 3 ->

Action 3;

Condition 4 ->

Action 4

true -> ... %保护断言%

end

举例:

[plain] view
plaincopy





-module(tmp).

-export([test_if/2]).

test_if(A, B) ->

if

A == 5 ->

io:format("A = 5~n", []),

a_equals_5;

B == 6 ->

io:format("B = 6~n", []),

b_equals_6;

A == 2, B == 3 -> %i.e. A equals 2 and B equals 3

io:format("A == 2, B == 3~n", []),

a_equals_2_b_equals_3;

A == 1 ; B == 7 -> %i.e. A equals 1 or B equals 7

io:format("A == 1 ; B == 7~n", []),

a_equals_1_or_b_equals_7

end.



% tmp:test_if(51,31). % 执行结果

% ** exception error: no true branch found when evaluating an if expression

% in function tmp:test_if/2 (tmp.erl, line 4)

2. case 语句

case 的格式

[plain] view
plaincopy





case conditional-expression of

Pattern1 -> expression1, expression2, .. ;,

Pattern2 -> expression1, expression2, .. ;

... ;

Patternn -> expression1, expression2, ..

end.

举例:

[plain] view
plaincopy





-module(temp).

-export([convert/1]).



convert(Day) ->

case Day of

monday -> 1;

tuesday -> 2;

wednesday -> 3;

thursday -> 4;

friday -> 5;

saturday -> 6;

sunday -> 7;

Other -> {error, unknown_day}

end.

3. when 语句

when 的格式

[plain] view
plaincopy





February when IsLeapYear == true -> 29;

February -> 28;

举例:斐波那契数列

[plain] view
plaincopy





% factorial(0) -> 1;

% factorial(N) -> N * factorial(N-1).



% 重写上面的函数,因为上面函数有个缺陷,当输入factorial(负数)会导致死循环

factorial(N) when N > 0 -> N * factorial(N - 1);

factorial(0) -> 1.

可以使用的条件:

判断数据类型(内建函数):is_binary, is_atom, is_boolean, is_tuple
比较运算符:==, =/=, <, >...
判断语句: not, and, xor......

4. Build-in Functions (BIFs) 内建函数

内建函数属于 erlang 模块的函数,直接调用或者间接调用都可以,比如 trunc 等同于 erlang:trunc

举例:
trunc:取整数部分
round:四舍五入
float:转化为浮点数
is_atom:判断是否为原子
is_tuple:判断是否为元组
hd/1:返回列表的第一个元素
tl/1:返回列表的最后一个元素
length/1:返回列表的长度
tuple_size/1:返回元组的大小
element/2:返回第n个元组的元素
setelement/3:替换元组中的某个元素,并返回新元组。stelement(要替换原子的位置,元组名,新原子的值)

erlang:append_element/2:添加一个原子到元组的末尾。(元组名,新原子的值)
类型转换

atom_to_list:原子转换为列表->字符串
list_to_atom:列表转换为原子
integer_to_list:整数转换为列表
list_to_tuple, tuple_to_list.
float, list_to_float, float_to_list, integer_to_list

5. 守卫

逗号:依次判断每个表达式为真,并向后执行

比如:guard2(X,Y) when not(X>Y) , X>0 -> X+Y % X<=Y 并且 X>0 时就执行 X+Y

分号:执行其中一个为真的表达式

比如:guard2(X,Y) when not(X>Y) ; X>0 -> X+Y % X<=Y 或者 X>0 时就执行 X+Y

6. 在if、case或receive原语中引入的变量会被隐式导出到原语主体之外
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: