loop exit question

Gunilla Hugosson gunilla@REDACTED
Thu Apr 19 14:27:26 CEST 2001


Klacke wrote:
> 
> On Thu, Apr 19, 2001 at 02:02:43PM +0200, Willem Broekema wrote:
> > If a function should loop forever while remembering some
> > state, most examples I have seen use:
> >
> > loop(State) ->
> >    receive
> >        stop ->
> >            stopped_upon_request;
> >        Other ->
> >            ...,
> >            loop(State)
> >    end.
> >
> > Now, if the State is not changed in any of the 'reveiced'
> > branches, is there a reason not to move the final 'loop()'
> > command to the end, and use 'exit()' for breaking out of
> > the loop, like in the following?
> >
> > loop2(State) ->
> >    receive
> >        stop ->
> >            exit(self(), stopped_upon_request);
> >        Other ->
> >            ...
> >    end,
> >    loop(State).
> >
> >
> 
> No, that's the way to do it.
> 

I disagree. You might be saved the effort of having to type
"loop(State)"  more than once, but you lose readability
and maintainability. I can't count the number of times I have
debugged code behaving strangely and found constructs like this:

loop(State) ->
  stop ->
    exit(stop);
  ...
  Pattern ->
    ...,
    loop(State);
  ...
  Other ->
     ignore
  end,
  loop(State).

/ Gunilla



More information about the erlang-questions mailing list