Enhanced type guard syntax]

Kenneth Lundin <>
Thu Sep 18 11:37:15 CEST 2003


Below follows a suggestion regarding enhanced syntax for
writing type guards in function clauses and in other match expressions.

I post this to see if you in the Erlang community have some (positive
or negative) opinions regarding this and I hope I get a lot of feedback.




Enhanced type guard syntax
---------------------------------------

The situation to day is that it is quite cumbersome to write type guards
for a function and that it
is unfair that some type constraints can be expressed directly in the
argument list (list, tuple,Binary)
while other type constraints must be expressed in the guard
(integer,atom,float,pid,port,fun) where the argument names have to be
repeated again.
The idea is originally from Mats Cronqvist AXD.

Examples as it is today:
------------------------

% The constraint that A and B must be integers
% must be expressed in the guard notation with the arguments repeated
%
foo(A, B) when integer(A), integer(B) ->
      A * B.

% The constraint that it must be a list (with at least one element)
% can be expressed directly in the argumentlist
%
bar([H|T]) ->
    H.



Proposed solution
------------------

Examples with new suggested syntax:
-----------------------------------

% The type constraint expressed directly in the argument list
% Shorter to write
% Exactly the same semantics as the foo example above
% The compiler has potential of handling these type constraints more
efficiently than today
% and this syntax makes the different type of guards more visible
%
foo(A/integer, B/integer) ->
      A * B.


{X/float, Y/float} = graph:coordinates(),

The rationale behind this suggestion is that we already have the
Variable/type syntax in the matchexpressions for binaries (example:
<<Size,B:Size/binary,Rest/binary>> = <<2,"AB","CD">>)
It is unfair that some types can be matched without guard syntax while
others can't.
It will result in a more compact and intuitive way of writing that will
encourage writing type constraints which will catch errors as early and
efficient as possible. The allowed type specifiers should be all the
type test BIFs named is_XXX/1 but without the "is_" prefix.

Alternative syntax
-------------------

Of course some other special character can be used to distinguish the
type constraint from other tokens and one idea could be to make this as
an extension to the '_' (don't care) notation which then indicates don't
care the value but it should be of a certain type.

foo(A = $integer, B = $integer) ->
      A*B.

foo(A = _$integer, B = _$integer) ->

Advantages with this solution could be that it does only introduce the
new variants of typed don't care.


/Regards Kenneth Lundin Product Manager of Erlang/OTP





More information about the erlang-questions mailing list