Enhanced type guard syntax]

Ulf Wiger (ÄL2/EAB) <>
Thu Sep 18 17:12:38 CEST 2003


On Sept 18 2003, Joe Armstrong <> wrote:
>
>  Adding  guards  like  this   violates  one  of  my  favorite  design
>meta-principles:
>
>  " If  you add something  to a language  you have to  chuck something
>away "
>
>  What are we going to chuck away?
>
>  Well not "when ->" ...
>
>  Since you can't say
>
>	foo(X, Y) when X == 2*Y ->
>
>  in the new syntax
>
>
>  Adding the new syntax without removing something will *increase* the
>complexity of the language. Since the change adds no semantic power
>I am against it.

In principle, I agree. However, one big problem with the 'when... ->'
syntax is that it's exceedingly ugly (well, at least exceedingly
cumbersome.)

The following code snippet from wings_deform.erl:

twist_fun(y, {Cx,_,Cz}) ->
    fun(U, Min, {X0,Y,Z0})
       when float(U), float(Min), float(X0), float(Y), float(Z0) ->
	    Angle = U*(Y-Min),
	    Cos = math:cos(Angle),
	    Sin = math:sin(Angle),
	    X = X0 - Cx,
	    Z = Z0 - Cz,
	    {X*Cos+Z*Sin+Cx,Y,Z*Cos-X*Sin+Cz}
    end;

would be possible to write as:

twist_fun(y, {Cx,_,Cz}) ->
    fun(U/float, Min/float, {X0/float, Y/float, Z0/float}) ->
        Angle = U*(Y-Min),
        Cos = math:cos(Angle),
        Sin = math:sin(Angle),
        X = X0 - Cx,
        Z = Z0 - Cz
        {X*Cos+Z*Sin+Cx,Y,Z*Cos-X*Sin+Cz}
    end;

which I personally think is a significant face lift.
Note for example that the complete function head in the 
second version is shorter than the guard declaration alone
in the first version. That, and the first version forces the
reader to jump back and forth in order to match the guards 
with the arguments.

In this particular code (I believe), type guards are important
from a performance perspective, since floating point operations
are performed more efficiently if the compiler can _know_ that
the input parameters are really floats.

In general, type guards should be used more because they add
safety and clarity. Unfortunately, with today's guard syntax,
they are unnecessarily clumsy, and can actually serve to 
obfuscate the code rather than clarifying it.

Also, it's consistent with the bit syntax, so the X/Type
syntax has already been added to the language.

For these reasons, I support the proposal.

/Uffe



More information about the erlang-questions mailing list