I have this if
statement:
if
A /= B -> ok;
true ->
end.
I want it to do nothing when A == B
.
Erlang does not have the notion of nothing
like void
or unit
. I would suggest returning another atom like not_ok
(or even void
or unit
.)
The best answer is don't use if, just use case.
case A of
B -> ok;
C -> throw({error,a_doesnt_equal_b_or_whatever_you_want_to_do_now})
end
typically ok
or undefined
or noop
are returned as atoms which mean essentially, nothing.
As said, any code will return something.
If you want to do something only in one case, then you can write this:
ok =if
A /= B -> do_something(A,B); % note that in this case do_something must return ok
true -> ok
end.
if you want to get new values for A, B you can write this
{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}
or in a more "erlang way"
%in your code
...
ok = do_something_if_different(A,B),
{NewA,NewB} = modify_if_different(A,B),
...
% and the definition of functions
do_something_if_different(_A,_A) -> ok;
do_something_if_different(A,B) ->
% your action
ok.
modify_if_different(A,A) -> {A,A};
modify_if_different(A,B) ->
% insert some code
{NewA,NewB}.
last if you expect that it crashes if 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With