[erlang-questions] Guards syntax for multiple values

Jesper Louis Andersen jesper.louis.andersen@REDACTED
Mon Mar 25 16:30:52 CET 2019


An alternative notation is that of or-patterns. Here from OCaml:

type foo = A | B | C | D

let is_frac x = match x with
    A | B | C -> true
    | _ -> false

Abusing erlang notation, you would write something like

is_frac(a);
is_frac(b);
is_frac(c) -> true;
is_frac(_) -> false.

for this variant. As for a hint why you would prefer an or-pattern over
list membership in a typed language, consider the compilation of

let is_frac x = match x with
    A | B | C | D -> true
    | _ -> false

This returns a warning: "Warning 11: this match case is unused." because
the latter wildcard match on _ can never be reached.



On Mon, Mar 25, 2019 at 3:27 PM Loïc Hoguin <essen@REDACTED> wrote:

> I would second this. It would be great to be able to say "when Val in
> [a, b, c]" and that be translated to "when Val =:= a; Val =:= b; Val =:=
> c" automatically. It's just nicer to read and write.
>
> And since strings are lists this would also work: 'when Val in
> "=!~._-"'. I have a lot of HTTP parsing code that would benefit from
> such a construct.
>
> I suppose "when Val in [a, b, c], Flag =:= true" would have to be
> translated as "Val =:= a, Flag =:= true; Val =:= b, Flag =:= true; Val
> =:= c, Flag =:= true" as well, due to how ;/, work in guards.
>
> Cheers,
>
> On 23/03/2019 04:24, Florent Gallaire wrote:
> > Hello everybody,
> >
> > I'm not very experimented in Erlang but I read carefully books and
> > official documention.
> >
> > It seems to me that the guards syntax is not as good as it should be,
> > i.e. too much verbose for multiple values.
> >
> > do(val1) -> val1;
> > do(val2) -> val2;
> > do(val3) -> val3;
> > do(val4) -> val4;
> > do(val5) -> val5.
> >
> > do(Val) when Val =:= val1; Val =:= val2; Val =:= val3; Val =:= val4;
> > Val =:= val5 -> Val.
> >
> > It's boring and error prone to write.
> >
> > Has a "in tuple" syntax already be considered ? Something like :
> >
> > do(Val) when Val in {val1, val2, val3, val4, val5} -> Val.
> >
> > Cheers
> >
> > Florent
> >
>
> --
> Loïc Hoguin
> https://ninenines.eu
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>


-- 
J.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20190325/9343a233/attachment.htm>


More information about the erlang-questions mailing list