0%

erlang 返回值

erlang函数返回的几种方式

case

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
case A of
true ->
case B of
true ->
case C of
true ->
ok;
false ->
error
end;
false ->
error
end;
false ->
error
end.

如果判断很多的话, 那么代码可读性就太差了

if

1
2
3
4
5
6
if
A -> ok;
B -> ok;
C -> ok;
true -> error
end

虽然代码看起来规整了,但是变量A,B,C必须先算出结果
性能是个问题

catch-1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
test() ->
catch test_f1().
test_f1() ->
case A of
false -> throw(error);
_ -> ok
end,
case B of
false -> throw(error);
_ -> ok
end,
case C of
false -> throw(error);
_ -> ok
end.

如果test_1/0存在逻辑报错,也会被catch
需要手动在test/0再加判断

catch-2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

-define(RETURN(Ret), throw({catch_return, Ret})).
-define(CATCH(A), mycatch(catch (A))).

mycatch({catch_return, Ret}) -> Ret;
mycatch({'EXIT', _Ret} = Catch) -> throw(Catch);
mycatch(Ret) -> Ret.

test() ->
?CATCH(
begin
case A of
false -> ?RETURN(error);
_ -> ok
end,
case B of
false -> ?RETURN(error);
_ -> ok
end,
case C of
false -> ?RETURN(error);
_ -> ok
end
end).

个人感觉这个比较好
catchcatch
throw的也throw