[erlang-questions] Why does Erlang have control structures?

Michael Richter <>
Tue Aug 28 04:50:40 CEST 2012

On 28 August 2012 04:56, Jayson Barley <> wrote:

> 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).
> I know that the control structures are a little bit faster, not much, but
> I find that the function form is more readable.

A case structure is like an *anonymous* function in this.  The use case for
them is the same as the use case for funs.

You had to come up with, even in your trivial example, two module-global
symbols: is_valid_signal/1 and switch_signal/1.  Take a non-trivial module,
now, and multiply it by the number of public API functions.  You'll start
getting name clashes as you go on.  For example, with your code above, what
happens if I want to tell a device to change the signal it's sending?  I
can't use switch_signal/1 any longer, so I have to use something like
change_signal/1 instead.  Now I've got two functions, switch_signal/1 and
change_signal/1, that look very similar by name.  I have to dig deeper to
figure out which does what if I'm maintaining the code base.  You could
argue that this is because switch_signal/1 is poorly named, but then it
falls right back into why case structures are useful: they're *anonymous*.
Anonymous constructs (cases, funs, etc.) are quite often very useful.

Further, your version of is_valid_signal/1 has a larger cognitive load.  In
the first case, if I want to know what is_valid_signal does and how it
works, I look up one function.  All the information I need to understand
the function is in one place.  With your solution this is now divided up
into multiple places.  There's more work to decode what's going on.  This
being a trivial function disguises the effect somewhat, but in a larger,
less trivial function this can be an impediment, again, to understanding
the code and reasoning about its behaviour.

"Perhaps people don't believe this, but throughout all of the discussions
of entering China our focus has really been what's best for the Chinese
people. It's not been about our revenue or profit or whatnot."
--Sergey Brin, demonstrating the emptiness of the "don't be evil" mantra.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20120828/7ab7ffdf/attachment.html>

More information about the erlang-questions mailing list