visibility of a function in a module

Joe Armstrong <>
Fri Apr 11 14:28:20 CEST 2003


> In this module, f(N) is a function visible in the entire module of test.
> % --------------------
> -module(test).
> -export([do/0]).
> 
> do() ->
>     go().
> 
> f(N) -> 
>     Base = 10,
>     Base + N.
> 
> go() ->
>     io:format("~w~n", [f(3)]).
> % ---------------------------



> But, I want to construct f() when do() is invoked.
> Now, I have the following module, in which F_() is not visible in
> the module.  And I need to pass it to go() through the parameter passing.
> Is this the only alternative ?
> % -----------------------------
> -module(test).
> -export([do/1]).
> 
> do(Base) ->
>     F_ = fun(N) -> Base+N end,
>     go(F_).
> 
> go(F) ->
>     io:format("~w~n", [F(3)]).
> % --------------------------------------
> 

Richard Carlsson made something like this (called Parameterised modules)

The idea is that you'd write:

   -module(test(Base)).
   -export([do/0]).

   f(N) ->
     Base + N.

   do() ->
	io:format("~w~n", [f(3)]

   --------

   To use this you'd do like this:

   M = load (test(Base)),
   M:do()

   This can be implemented by some relatively simple code transformations.

   However you look at it there is no way of statically binding a dynamically
created fuction to a name - you have to store it in some variable F and
carry it round the computation until you wish to use it and then say F(Args)

   There are of course many many ways of doing this ...

   f(Base) ->
	put(dingo, fun(N) -> N + Base end).

   do() ->
	io:format("~w~n", [(get(dingo))(3)].

   Does the same as your code in a way that is not "recommended" (TM) 
by some :-)

   /Joe






More information about the erlang-questions mailing list