New EEP draft: Pinning operator ^ in patterns

Attila Rajmund Nohl attila.r.nohl@REDACTED
Mon Dec 28 13:21:27 CET 2020

Richard Carlsson <carlsson.richard@REDACTED> ezt írta (időpont: 2020.
dec. 24., Cs, 21:10):
> The ^ operator allows you to annotate already-bound pattern variables as ^X, like in Elixir. This is less error prone when code is being refactored and moved around so that variables previously new in a pattern may become bound, or vice versa, and makes it easier for the reader to see the intent of the code.
> See also
> But
> suppose that someone adds a binding of the name `T` further up in the
> function body, without noticing that the name is already in use:
>   g(Stuff) ->
>       ...
>      T = q(Stuff) + 1,
>       io:format("~p", [p(T)]),
>       ...
>       Thing = case ... of
>                   {a, T} -> T;
>                   _ -> 0
>               end,
>       ...
>       {ok, [Thing|Stuff]}.
> Now the first clause of the case switch will only match if the second
> element of the tuple has the exact same value as the previously
> defined `T`.

I admit I had a similar bug a couple of months ago. Took some time to
find it, so I see the rationale to introduce an option to tell the
compiler "I expect the variable to be pinned here". But I don't think
this is the right approach to avoid these kinds of bugs. The ^
operator must be optional at introduction (to avoid breaking lots of
legacy code), but if it's optional, it's usage will be also optional -
and more importantly inconsistent. Some codebases will use, some not
and in the worst case it's usage could be on a function-by-function
clause, meaning that if I don't see the ^ operator in code like above,
I can't be sure it was intentionally or accidentally left out. I'm not
sure that a code like

case ... of
  {a, ^T} -> T;

will be more clear than

case ... of
  {a, TempT} when T == TempT -> TempT;

For this later case we don't need a new operator and the code would be
more consistent with the idioms used in funs to avoid shadowing.

> Ho ho ho,
>         /Richard & the good folks at WhatsApp

More information about the erlang-questions mailing list