franco mocci
franco mocci

Reputation: 165

comparison using if with erlang

I work with erlang

I want to make a function that will check if the Cin and Id is not null

I tried with:

if Cin /= null && Id/=null -> {ok,Cin et Id sont différents de null};
     true -> {nok,Cin et Id sont  null}

    end.

I know that the notion of '&&' does not exist in erlang

but I can not find the equivalent of this notion in erlang

Upvotes: 0

Views: 311

Answers (3)

vkatsuba
vkatsuba

Reputation: 1449

You can create function and use pattern matching:

is_null(null, null) ->
  true;
is_null(_, _) ->
  false.

in console:

1> c(some_mod).
{ok,some_mod}
2> some_mod:is_null(null, 1).
false
3> some_mod:is_null(1, 1).   
false
4> some_mod:is_null(null, null).
true

Upvotes: 2

I GIVE CRAP ANSWERS
I GIVE CRAP ANSWERS

Reputation: 18859

Usually, it is better to use a match:

case {Cin, Id} of
  {null, _} -> cin_null;
  {_, null} -> id_null;
  {_, _}    -> not_null
end

But also note that you can get away with not checking at all. Add a guard in the function head:

my_func(Cin, Id) when is_integer(Cin), is_binary(Id) ->
  do_something.

If this fails to match, you have a crash, but this is usually what you expect to happen in the code base.

Upvotes: 6

Greg Hewgill
Greg Hewgill

Reputation: 992857

In Erlang, use andalso instead of &&:

if Cin /= null andalso Id/=null -> {ok,Cin et Id sont différents de null};

The use of andalso is short-circuiting and is equivalent to &&. The regular and operator always evaluates both sides of the expression and is not short-circuiting.

Upvotes: 6

Related Questions