Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang: How to "Do Nothing" in true branch of if statement

I have this if statement:

if 
    A /= B -> ok;
    true   ->
end.

I want it to do nothing when A == B.

like image 802
itamar Avatar asked Apr 09 '13 22:04

itamar


3 Answers

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.)

like image 186
Brett Forsgren - MSFT Avatar answered Nov 13 '22 02:11

Brett Forsgren - MSFT


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.

like image 7
inaka Avatar answered Nov 13 '22 01:11

inaka


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.
like image 3
Pascal Avatar answered Nov 13 '22 03:11

Pascal