[erlang-questions] guard expression restriction

Richard O'Keefe ok@REDACTED
Thu Dec 2 04:16:51 CET 2010


On 2/12/2010, at 7:22 AM, James Churchman wrote:

> Interestingly list comprehensions offer custom guards, if that it of use to you.

And what a disaster THAT is.
Consider

	1> 1+a > 2.
	** exception error: bad argument in an arithmetic expression
	      in operator +/2
                 called as 1 + a

In a *guard*, this would be a silent failure.
As an expression (which it should never have been allowed to be),
exceptions are raised and propagated through > .

	2> [X || X <- lists:seq(1,100), X+a > 2].
	[]

Here the exception became a silent failure.  So the guard is a guard.


	3> math:cos(foo) > 1.
	** exception error: bad argument
	     in function math:cos/1
	        called as math:cos(foo)

	4> [X || X <- lists:seq(1,100), math:cos(foo) > X].
	** exception error: bad argument
	     in function math:cos/1
		called as math:cos(foo)

Here the exception did NOT become a silent failure!

If the guards in list comprehensions are GUARDS, then *any*
exception inside one should turn into a silent failure, and
query 4 should have the answer [] with no carping.

If the guards in list comprehensions are EXPRESSIONS, then
every expression inside one should be propagated, and query
2 should have raised an exception.

It's even worse.  If guards in list comprehensions had been
guards, we'd have been able to use Pattern = Expression to
bind variables locally inside comprehensions, instead of
having to use the kluge Pattern <- [Expression].

Inconsistent treatment of tests in comprehensions like this
is a real menace.  I would value some kind of static check
that the guards in comprehensions are proper guards.






More information about the erlang-questions mailing list