[erlang-questions] closure on function argument
Richard O'Keefe
ok@REDACTED
Mon May 3 01:33:49 CEST 2010
On May 2, 2010, at 8:56 AM, Robert Virding wrote:
> The variables in the arguments of a fun, Y in your example, are always
> "fresh" variables and never imported from the funs environment.
For me personally, this is perhaps THE most confusing thing
about Erlang.
I have *no* problem with the same rule in ML or Haskell because they
apply it *consistently*: every pattern everywhere introduces fresh
variables, it is never ever possible in those languages for a
variable occurrence in a pattern to be an applied occurrence; all
pattern variables are binding occurrences. This applies to OCaml and
Clean as well.
But Erlang does NOT apply this rule consistently.
Variables in a pattern of a 'case' are *not* fresh, they *may* be
applied occurrences. And even in a fun, *some* variable occurrences
may be applied ones: fun (Y,Y) -> ... end.
It's especially confusing because variables in fun bodies and guards
are imported as usual, so they are clearly in scope.
It would be *so* nice if ALL variables in Erlang followed exactly
the same rules.
Here's a little example. Suppose someone has
case E of P -> B end
but doesn't want any variable bindings in B to be exported.
The obvious thing to do is to rewrite it as
(fun (P) -> B end)(E)
but because Erlang is inconsistent here, that does not work.
(You can patch around it with fun, case, and a new variable,
but that has problems of its own.)
I have never been able to see any merit in this rule; its effect
on me is to make it harder to write funs because I always have to
watch out for cases where the expected thing won't happen and it
has to be patched around.
More information about the erlang-questions
mailing list