[erlang-questions] Why does Erlang have control structures?
黃耀賢 (Yau-Hsien Huang)
<>
Tue Aug 28 18:50:02 CEST 2012
On Tue, Aug 28, 2012 at 4:56 AM, Jayson Barley <>wrote:
> I am not sure I understand why we have them. For instance I can take the
> following code
>
> is_greater_than(X, Y) ->
> if
> X>Y ->
> true;
> true -> % works as an 'else' branch
> false
> end.
>
> And make it
>
> is_true(true) ->
> true;
> is_true(false) ->
> false.
>
> is_greater_than(X, Y) ->
> is_true(X>Y).
>
> Your is_true/1 means that it may meet either true, false, or other values.
However, 'if' statement means that it would meet two cases definitely.
is_true/1 is an identity function (fun(X) -> X end) working on Boolean
values.
Then it may be is_true(X>Y) or is_true(is_true(X>Y)) or
is_true(is_true(is_true(is_true(is_true(is_true(X>Y)))))).
Eventually, It is (X > Y).
> I can do the same thing with case statements
>
> is_valid_signal(Signal) ->
> case Signal of
> {signal, _What, _From, _To} ->
> true;
> {signal, _What, _To} ->
> true;
> _Else ->
> false
> end.
>
> Becomes
>
> switch_signal({signal, _What, _From, _To}) ->
> true;
> switch_signal({signal, _What, _To}) ->
> true;
> switch_signal(_Else) ->
> false.
>
> is_valid_signal(Signal) ->
> switch_signal(Signal).
>
>
is_valid_signal(Signal) ->
case Signal of
{signal, _What, _From, _To} ->
true;
{signal, _What, _To} ->
true;
_Else ->
false
end.
The above is an alternative version of
is_valid_signal({signal, _What, _From, _To}) ->
true;
is_valid_signal({signal, _What, _To}) ->
true;
s_valid_signal(_Else) ->
false.
Don't repeat it.
> I know that the control structures are a little bit faster, not much, but
> I find that the function form is more readable.
>
> _______________________________________________
> erlang-questions mailing list
>
> http://erlang.org/mailman/listinfo/erlang-questions
>
>
In my opinion, 'if' block limits the domain, and 'case' block provides
a way more writable than to write many function heads to pick its
matching patterns.
--
Best Regards.
--- Y-H. H.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20120829/3ff5c600/attachment.html>
More information about the erlang-questions
mailing list