Reputation: 47
Boolean x = true;
int y = 1;
int z = 1;
if(y ==1 && x == true){
z++;
x = false;
}
else{
z--;
x = true;
}
I want to do this in erlang.. How Can I do this? (Please be noted that this is a example code. What I want to do are two conditions in one if statement & this boolean functionality). Any help is welcomed.Actually z-- & z++ are not needed.
Upvotes: 1
Views: 1873
Reputation: 48649
Boolean x = true;
...
x = false;
That's never going to happen in erlang. Erlang variables can only be assigned to once, which also means that you can't do var++
and var--
in erlang.
You can use what are called guards in the head of a function clause to employ boolean filters on the function arguments. In a guard, a comma acts like &&
in other languages and a semi-colon acts like ||
.
-module(my).
-compile(export_all).
guard: Y==1 && X
+----------+
| |
| |
go(X, Y) when Y==1, X ->
false;
go(_, _) ->
true.
go_test() ->
false = go(true, 1),
true = go(false, 1),
true = go(true, 20),
all_tests_passed.
In the shell:
~/erlang_programs$ erl
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]
Eshell V9.3 (abort with ^G)
1> c(my).
my.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,my}
2> my:go_test().
all_tests_passed
3>
Per Wotjek Surowka, go/2
can be written more simply without guards. Because there is only one combination of arguments where the result is false
, while all other combinations of arguments produce a true
result, you can write:
go(true, 1) ->
false;
go(_, _) ->
true.
Upvotes: 2
Reputation: 401
If you program functional language, especially Erlang, please avoid even thinking about if statement, although Erlang case supports that.
Always think of pattern match.
Upvotes: 2
Reputation: 916
You may use case statement
*this example will always returl tuple with two elements {Z, X}
case_statement() ->
X = true,
Y = 1,
Z = 1,
case {Y, X} of
{1, true} ->
{Z + 1, false};
_ ->
{Z -1, true}
end.
If you need to use exact 'if' statement here is the example
if_statement() ->
X = true,
Y = 1,
Z = 1,
if
Y =:= 1 andalso X =:= true ->
{Z +1, false};
true ->
{Z -1, true}
end.
Upvotes: 3