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