LYSE-函数语法

模式匹配

函数声明可以由函数从句构成。

函数从句用";"分隔。

几个函数通过模式匹配,实现分支逻辑。

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]).

 

io:fromat使用标记来格式化字符串的输出。

一些常用的标记:

  ~n 换行

  ~s 代表后面的string或bitstring参数

  ~p 按标准格式打印Erlang代码

io:format("~s~n",[<<"Hello">>]).

io:format("~p~n",[<<"Hello">>]).

io:format("~~~n").

io:format("~f~n", [4.0]).

io:format("~30f~n", [4.0]).

 

守卫

为了匹配一个区间值,可以使用守卫:

old_enough(X) when X >= 16 -> true;
old_enough(_) -> false.

与逻辑的守卫:

right_age(X) when X >= 16, X =< 104 ->
true;
right_age(_) ->
false.

或逻辑的守卫:

wrong_age(X) when X < 16; X > 104 ->
true;
wrong_age(_) ->
false.

在守卫表达式中,","相当于andalso,";"相当于orelse。

但也有区别。

  ","、";"会捕获异常,而andalso、orelse不会。

  在"A;B"中,A抛出异常,会继续对B求值,如果B为真会返回真。

  在"A orelse B"中,A抛出异常,则守卫表达式不匹配。

 

  而只有andalso、orelse可以在守卫表达式中嵌套使用。

  即可以写:(A orelse B) andalso C

  不可以写:(A;B),C

 

if语句

%% note, this one would be better as a pattern match in function heads!
%% I'm doing it this way for the sake of the example.
help_me(Animal) ->
Talk = if Animal == cat  -> "meow";
Animal == beef -> "mooo";
Animal == dog  -> "bark";
Animal == tree -> "bark";
true -> "fgdadfgna"
end,
{Animal, "says " ++ Talk ++ "!"}.

 

case语句

insert(X,[]) ->
[X];
insert(X,Set) ->
case lists:member(X,Set) of
true  -> Set;
false -> [X|Set]
end.

复杂一点的

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.

 

转载于:https://www.cnblogs.com/sqxy110/p/4996917.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值