Question about fun's

Martin Bjorklund mbjk@REDACTED
Wed Jan 27 22:08:33 CET 1999


Shawn Pearce <pearcs@REDACTED> wrote:

> Essentially parts of the system will need to invoke code on some
> plugin module whose name isn't known until runtime, and even then
> will change on invoctions.

This is a pretty common situation in generic Erlang programs - use a
callback module (which may change dynamically) and call a certain
function in that module at certain occasions.  One example is the
module gen_server, which implements a generic server process.  The
server is given the name of a callback module when the process is
started.  For each request the server receives, a function in the
callback module is called:


-module(gs).

start(Mod) -> spawn(gs, init, [Mod]).

init(Mod) ->
   InitState = Mod:init(),
   loop(Mod, InitState).

loop(Mod, State) ->
   receive
      {request, From, Req} ->
          {Reply, NewState} = Mod:handle_request(Req, State),
          From ! Reply,
          loop(Mod, NewState);
      {change_module, NewMod} ->
          loop(NewMod, NewState)
  end.


-module(callback1).

init() -> [];

handle_request({append, Item}, State) ->
  {ok, State ++ Item};

handle_request(print, State) ->
  io:format("~p", [State]),
  {ok, State}.


etc.



> We'll implement each class in its own module, but we really sort of need the
> ability to have methods dispatched based on the class at runtime, rather than
> at the time of the coding.

Mod:handle_request(Mod) is an example of that.  It is just a syntactic
sugar for apply(Mod, handle_request, [Mod]).

Also, the function name could be dynamic:

Mod:Fun(...)   works just fine.



/martin



More information about the erlang-questions mailing list