Why pattern matching on map key in function arguments causes an unbound error?

Can someone explain why the pattern match in function arguments on map keys is invalid? e.g.:

1> F = fun(#{key := Key}, #{Key := Value}) -> Value end.
* 1:16: variable 'Key' is unbound

But this is valid:

2> F = fun(#{key := Key}, Map) -> #{Key := Value} = Map, Value  end.
#Fun<erl_eval.41.3316493>
2 Likes

IIRC there are no guarantees that bindings will be evaluated left to right as written in the function head. If there was it would put restrictions on how the function head would be translated into core erlang and possibly disallow certain optimisations (like evaluating the likely cheapest pattern match first irrespective of where in the function head it occurs).

Or something a bit like that.

7 Likes

Thanks, @kjnilsson!

1 Like