If statement 二郎:如何;“什么也不做”;if语句的in-true分支

If statement 二郎:如何;“什么也不做”;if语句的in-true分支,if-statement,erlang,If Statement,Erlang,我有一个if语句: if A/=B->ok; 正确-> 结束。 当Erlang没有像void或unit这样的nothing概念时,我希望它什么也不做。我建议返回另一个原子,如not_ok(甚至void或unit)最好的答案是不使用if,只使用case case A of B -> ok; C -> throw({error,a_doesnt_equal_b_or_whatever_you_want_to_do_now}) end 通常ok或undefined或noop

我有一个
if
语句:

if
A/=B->ok;
正确->
结束。

当Erlang没有像
void
unit
这样的
nothing
概念时,我希望它什么也不做。我建议返回另一个原子,如
not_ok
(甚至
void
unit

最好的答案是不使用if,只使用case

case A of
   B -> ok;
   C -> throw({error,a_doesnt_equal_b_or_whatever_you_want_to_do_now})
end

通常
ok
undefined
noop
作为原子返回,基本上没有任何意义。

如前所述,任何代码都会返回一些东西

如果您只想在一种情况下做某件事,那么您可以这样写:

ok =if 
    A /= B -> do_something(A,B); % note that in this case do_something must return ok
    true -> ok
end.
如果你想得到A,B的新值,你可以写这个

{NewA,NewB} = if 
    A /= B -> modify(A,B); % in this case modify returns a tuple of the form {NewA,NewB}
    true -> {A,B} % keep A and B unchanged 
end.
% in the following code use only {NewA,NewB}
或者以更“erlang方式”

最后,如果您希望它在A==B时崩溃

%in your code
...
ok = do_something_if_different_else_crash(A,B),
...


% and the definition of functions
do_something_if_different_else_crash(A,B) when A =/= B ->
    % your action
    ok.

是的,一切都会返回一个值。您不能返回值。除非您引发异常并且不处理它,否则我不希望任何atom返回。我只需要在第一个条件为真的情况下做一个运算。原子什么都不做,所以你当前问题的答案是正确的。你解决的问题与你要求的不同。向我们展示真实的代码,您将得到所需的答案。@itamar我必须说过,您将始终得到一个返回值!它是一种函数式语言,所有内容都是一个返回值的表达式。即使你只是为了它的副作用而做一些事情,它仍然会返回一个值。您不能不返回值!如果不使用第二个分支,为什么不使用
case
并将其省略
if
根本不起作用。@ckruse您不能忽略它,因为
case
,与
if
相同,如果没有匹配的模式,就会生成错误。Erlang没有默认的返回值,您必须始终处理每种情况。
%in your code
...
ok = do_something_if_different_else_crash(A,B),
...


% and the definition of functions
do_something_if_different_else_crash(A,B) when A =/= B ->
    % your action
    ok.