erlang的case和if

case Expr of
    Pattern1 [when Guard1] -> Seq1;
    Pattern2 [when Guard2] -> Seq2;
    ...
    PatternN [when GuardN] -> SeqN
end

首先,对Expr求值,然后,Expr的值将依次与模式Pattern1Pattern2……PatternN进行匹配,直到匹配成功。如果找到一个匹配并且(可选的)的保护式成立,则对应的调用序列将被求值。注意case保护式与函数保护式形式相同。case原语的值就是被选中的序列的值。

举个例子,比方说我们我有个函数allocate(Resource)用于分配某种资源Resource。假设这个函数只返回{yes, Address}no。这样,这个函数便可以放在一个case结构里:

case allocate(Resource) of
    {yes,Address} when Address > 0, Address => Max ->
        Sequence 1 ... ;
    no ->
        Sequence 2 ...
end

如果没有匹配项,则会引发错误,所以我们经常这样写:

case allocate(Resource) of
    {yes,Address} when Address > 0, Address => Max ->
        Sequence 1 ... ;
    no ->
        Sequence 2 ...;
     _ ->
        true
end


if
    Guard1 ->
        Sequence1 ;
    Guard2 ->
        Sequence2 ;
    ...
end
在这种情况下,保护式Guard1,...将被依次求值。如果一个保护式成立则对与之关联的序列求值。该序列的求值结果便是if结构的结果。if保护式与函数保护式形式相同。与case相同,一个保护式都不成立的话将引发一个错误。如果需要,可以增加保护式断言true作为垃圾箱:
test(A)->
	B=if 
		is_float(A)->
			A*10;
		is_list(A)->
			A;
		true->
		true
	end,
B.


转:http://www.erlang-cn.com/242.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章