[erlang-questions] eep: multiple patterns
Richard A. O'Keefe
ok@REDACTED
Fri May 30 00:17:19 CEST 2008
On 29 May 2008, at 6:44 pm, Ulf Wiger (TN/EAB) wrote:
> It seemed to me as if the thread was approaching
> the idea of
>
> receive Msg ->
> case classify_msg(Msg) of
> Type -> Action
> ...
> end.
This is due to an accident: one example we were given
_did_ have a receive that was going to handle every
possible message (there was an X-> case at the end).
I wanted to concentrate on the "two cases" idea and
not on receiving.
> Maybe it's another thread altogether, but, I was
> under the impression that abstract patterns could
> actually help this situation (too) somewhat.
Yes they can. I think I mentioned that, but I
wanted to show that the problem can be handled
without excessive pain in the language as it stands.
Let's take the running example:
loop(State) ->
case receive
quit -> quit
; {?MODULE,{signal,{window1,_}}} -> quit
; {?MODULE,{signal,{quit1,_}}} -> quit
; {?MODULE,{signal,{connect,_}}} -> connect
; {?MODULE,{signal,{disconnect,_}}} -> disconnect
; {?MODULE,{signal,{about1,_}}} -> show_about
; {?MODULE,{signal,{dialog1,_}}} -> hide_about
; {?MODULE,{signal,{dialogb,_}}} -> hide_about
; {data,Data} -> {data,Data}
; X -> {error,X}
end
of quit -> quit()
; connect -> loop(conn(State))
; disconnect -> loop(disc(State))
; show_about -> loop(show_about(State))
; hide_about -> loop(hide_about(State))
; {data,D} -> loop(update(State, D))
; {error,X} -> io:fwrite("got ~p~n", [X]),
loop(State)
end.
Now let's do it with abstract patterns.
#quit() -> quit;
#quit() -> {?MODULE,{signal,{window1,_}}};
#quit() -> {?MODULE,{signal,{quit1,_}}}.
#connect() -> {?MODULE,{signal,{connect,_}}}.
#disconnect() -> {?MODULE,{signal,{disconnect,_}}}.
#show_about() -> {?MODULE,{signal,{about1,_}}}.
#hide_about() -> {?MODULE,{signal,{dialog1,_}}};
#hide_about() -> {?MODULE,{signal,{dialogb,_}}}.
#data(Data) -> {data,Data}.
loop(State) ->
receive
#quit() -> quit()
; #connect() -> loop(conn(State))
; #disconnect() -> loop(disc(State))
; #show_about() -> loop(show_about(State))
; #hide_about() -> loop(hide_about(State))
; #data(Data) -> loop(update(State, Data))
; X -> io:fwrite("got ~p~n", [X]),
loop(State)
end.
From one point of view, of course, this simply *IS*
multiple patterns. But the complexity has to be moved
out of the case or receive or whatever and given a *NAME*.
Once again we are separating "what is to be done" from
"how to do it", making it easier to understand each.
More information about the erlang-questions
mailing list