Raj*_*aja 0 erlang if-statement
试图计算得分并将其维持在0.2到1.5之间.以下代码是否有效?我不希望它返回,但继续进一步.
ok = if
Score > 1.5 ->
Score = 1.5;
true ->
ok
end,
ok = if
Score < 0.2 ->
Score = 0.2;
true ->
ok
end,
put(score, Score),
Run Code Online (Sandbox Code Playgroud)
以下代码是否有效?
不.在erlang中,您只能分配一次变量.这是你应该学到的第一件事.在这个声明中:
if
Score > 1.5 -> ...
Run Code Online (Sandbox Code Playgroud)
已经为变量Score分配了一个值,您将其与小数1.5进行比较.假设Score的值为2.0,那么该特定if子句的主体执行:
Score = 1.5;
Run Code Online (Sandbox Code Playgroud)
这相当于写作:
2.0 = 1.5;
Run Code Online (Sandbox Code Playgroud)
这将导致模式匹配错误:
- 异常错误:右侧值1.5不匹配.
在erlang中,一旦为变量赋值,之后对该变量的任何后续赋值都将被视为模式匹配,即等号右边的值将与等于左边的值进行模式匹配.标志.
在erlang中,通常使用多个函数子句来模式匹配不同的值:
-module(my).
-compile(export_all).
compute(Score) when Score > 1.5 ->
1.5;
compute(Score) when Score < 0.2 ->
0.2;
compute(Score) ->
Score.
Run Code Online (Sandbox Code Playgroud)
在shell中:
1> c(my).
my.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,my}
2> Score1 = my:compute(1.6).
1.5
3> Score2 = my:compute(1.5).
1.5
4> Score3 = my:compute(1.2).
1.2
5> Score4 = my:compute(0.1).
0.2
6> Score5 = my:compute(0.2).
0.2
Run Code Online (Sandbox Code Playgroud)
然后你可以在同一个模块中定义另一个函数,如下所示:
do_stuff(Score) ->
NewScore = compute(Score),
%Do something with NewScore here...
Run Code Online (Sandbox Code Playgroud)
如果你想使用if语句,我会这样做:
-module(my).
-compile(export_all).
do_stuff(Score) ->
NewScore = if
Score > 1.5 -> 1.5;
Score < 0.2 -> 0.2;
true -> Score
end,
%Do something with NewScore here, for instance:
io:format("~w~n", [NewScore]).
Run Code Online (Sandbox Code Playgroud)
为了使您的函数不超过5-6行,将if语句移动到另一个函数中会有所帮助.