[erlang-questions] : abstract patterns vs macros was:( Floating guard sequences)

Richard O'Keefe ok@REDACTED
Mon Feb 23 01:49:56 CET 2009

On 21 Feb 2009, at 12:01 am, Zvi wrote:

> I like Abstract Patterns, I think they make patterns more like first- 
> class
> citizens and make ADTs implementation easier. There several  
> comments, which
> I'll write later. For now, I just trying to write simple abstract  
> pattern
> for inclusive range of integers:
> #range(N,M) when is_integer(X) -> N=<X, X<=M.
> I just introduced X. Is this right way?

An abstract pattern lets you name and reuse a combination of
pattern match and type test that you could have written without it.

The form of a pattern definition is
	#<head> when <guard> -> <pattern>.

In this case, N =< X, X =< M is a guard, not a pattern.
I think what you want is

	#range(L, U, X)
	when is_integer(X), L =< X, X =< U
	-> X.

Without abstract patterns, you would write
	f(..., X, ...) when is_integer(X), L =< X, X =< U ... ->
	       ^rhs         ^guard......................^
The bit you would have written in the head of a function clause
goes on the right of the arrow, and the bit that would have
been in the guard of a function clause goes in the guard of the

> Do I need to specify is_integer(N), is_integer(M) for abstract pattern
> arguments too ?

Only if you want to.  The one thing you cannot do is solve for
the bounds.  Any variable in the head of a pattern that does not
occur in the right hand side must be bound some other way.
So you can do

	f(N, #range(1,N, X)) -> ...
or	f(N, #range(1,N, 42)) -> ...
but not
	g(#range(1,N, 42)) -> ... N ...

More information about the erlang-questions mailing list