[erlang-questions] closure on function argument

Robert Virding rvirding@REDACTED
Sat May 1 22:56:44 CEST 2010


The variables in the arguments of a fun, Y in your example, are always
"fresh" variables and never imported from the funs environment. If you
wanted to generate a fun which matches against variables imported from
its environment then you need to put an explicit test in the guard. In
your case:

F = fun(Y) -> fun(Y1) when Y1 == Y -> ok end end.

Then you get

8> F = fun(Y) -> fun(Y1) when Y1 == Y -> ok end end.
#Fun<erl_eval.6.13229925>
9> G = F(z).
#Fun<erl_eval.6.13229925>
10> G(z).
ok
11> G(a).
** exception error: no function clause matching
                    erl_eval:'-inside-an-interpreted-fun-'(a)
12>

Robert


On 1 May 2010 20:38, Zoltan Lajos Kis <kiszl@REDACTED> wrote:
> Hi,
>
> If I have /F = fun(Y) -> fun(Y) -> ok end end/, and /G = F('z')/, I would
> expect /G/ to be /fun('z') -> ok end/.
> Apparently, it is /fun(Y) -> ok end/, as calling it with any argument
> returns /ok/ and never causes a function clause exception.
> I guess that the inner /Y/ being an argument "automatically" shadows the
> outer one.
>
> A workaround I found is using guards: /F = fun(Y) -> fun(X) when X == Y ->
> ok end end/.
> The question is: is there a way to create a direct binding between the inner
> and outer /Y/'s in the original example?
>
> Thank you,
> Zoltan.
>
>
>


More information about the erlang-questions mailing list