[erlang-questions] Floating guard sequences

Zvi exta7@REDACTED
Thu Feb 19 21:22:15 CET 2009




fess-3 wrote:
> 
> ...
> floating guards on the LHS of a match seem like they could make  
> code much more concise and readable, and erlang-like [ to me ]
> 
> 
>    { X when is_integer(X), [ "x" | Rest ] } = string:to_integer(Str),
>    { Y when is_integer(Y), _ } = string:to_integer(Rest),
> 
  
 much more readable, if we can marry patterns with guards:

   { X = int(), [ "x" | Rest ] } = string:to_integer(Str),
   { Y = int(), _ } = string:to_integer(Rest),

where int() is patten matching any integer value.
Or, if X and Y unused, like in the example above:

   { int(), [ "x" | Rest ] } = string:to_integer(Str),
   { int(), _ } = string:to_integer(Rest),

similarly, pattern for each data type are needed (i.e. atom(), float(),
pid(), ref(), fun(), etc.)
Instead of  writing something, like:

   map(F,L) when is_function(F,1) -> ...
you can write:
   map(F = fun(_), L)  -> ...

or instead of:

  reduce(F,L) when is_function(F,2), is_list(L) -> ...
you can write:
  reduce(F = fun(number(),number()), L = list()) -> ...

Then patterns can be extended to ranges, i.e. instead of:

  month(M) when is_integer(M), 1=<M, M<=12 -> ...
you can write something like:
  month(M = 1..12)  -> ...

or
  is_natural(1..inf) -> true;  % inf - is reserved word for infinity range
  is_natural(num()) -> false.

etc.

Also I think it can be usefull to implement doxygen, like edoc:

  reduce(F = fun(number(),number()),  %@@ function that takes two numbers
and returns number
            L = list())                            %@@input list of numbers
            -> ...

Is short, pattern defines set of values, that will match it. In the same way
as type defines set of values, which belongs to it. 
Also if pattern defines (ordered) set, it can be used for iteration, i.e.:

[ month_name(Month) || Month <- 1..12 ]

So, I propose to use the same construct for:
1. Construction of values  (literal constructs value of itself)
2. Pattern matching  (literal matches itself)
3. Dynamic type declaration
4. Iterators

I think it's much more Erlangish way, than type specs.

Zvi

-- 
View this message in context: http://www.nabble.com/Floating-guard-sequences-tp22067566p22108890.html
Sent from the Erlang Questions mailing list archive at Nabble.com.




More information about the erlang-questions mailing list