[eeps] EEP XXX: Pattern-test operator
Richard O'Keefe
ok@REDACTED
Mon Apr 30 08:52:57 CEST 2012
On 30/04/2012, at 1:59 PM, David Mercer wrote:
> You actually answered that quite well, and I understood your answer. I was just trying to understand *why* or *when* binding in guards might be necessary.
That's described in Erik Søe Sørensen's original proposal.
Here's an example, adapted from one of his.
?point_in_unit_square(P)
is to succeed as a guard if and only if P is a {point,X,Y}
term and X and Y are both floating point numbers in the
half-open interval [0.0,1.0).
This is duck soup for abstract patterns.
#point_in_unit_square(X, Y)
when is_float(X), 0.0 =< X, X < 1.0,
is_float(Y), 0.0 =< Y, Y < 1.0
-> {point,X,Y}.
It is straightforward in Erlang with '?=' as the only
extension:
-define(point_in_unit_square(P),
( {point,X,Y} ?= P andalso
is_float(X) andalso 0.0 =< X andalso X < 1.0 andalso
is_float(Y) andalso 0.0 =< Y andalso Y < 1.0
)).
But without ?= you have to write
-define(point_in_unit_square(P),
( is_tuple(P) andalso
tuple_size(P) =:= 3 andalso
element(1,P) =:= point andalso
is_float(element(2,P)) andalso
0.0 =< element(2,P) andalso
element(2,P) < 1.0 andalso
is_float(element(3,P)) andalso
0.0 =< element(3,P) andalso
element(3,P) < 1.0
)).
One would expect a good compiler to evaluate element(2,P) once
rather than three times, but that amounts to doing
X ?= element(2, P) in the object code, so why not in the source
code?
Following this example, you will see that it is easy to come
up with examples that take O(n) tokens to write using ?= but
O(n**2) without.
More information about the eeps
mailing list