[erlang-questions] guards

Johnny Billquist bqt@REDACTED
Sat Jul 25 11:51:48 CEST 2009

Dave Pawson wrote:
> 2009/7/25 Johnny Billquist <bqt@REDACTED>:
>>>> It is little bit overcomplicated version of
>>>> filterHelper([X], Int, Result) when X =< Int -> [X|Result];
>>> Mmm. Thanks... I think :-)
>>> (I'm trying to learn!)
>>> Does that check for a list length of 1?
>> A pattern of [X] can only match a list with one element.
> Couldn't X be a variable which might be a tuple or ... almost anything?
> Or is this pattern matching logic, that implies it is as you say?

I'm making the assumption that X is unbound at the time, otherwise we 
have a different ballgame where much less will match (in fact, only a 
list, of which the only element is identical to whatever X is bound to).

The *only* element in the list could, however, be a list, a tuple, or 
just about anything. There is no limits to what it could be. The point 
is, that that is the only element in the list. If you want to check 
further into what type of element you have in the list, then you could 
either expand the pattern more, or add guards. Guards are useful when 
you want to check some general property of the element, but for explicit 
details, pattern matching makes more sense.

Assume that the list should hold just one element, and that one element 
should be a tuple with two elements. That would then match against the 
pattern [{X,Y}]

If the first element of the tuple should be 'foo', then the pattern 
could be [{foo,X}]

No need to use guards to check for that. However, if the list should 
hold one element, and that should be a tuple, but you don't know what 
kind of tuple, then you'd need a guard, as in:

foo([X]) when is_tuple(X) ->

because the pattern can't specify a tuple with a variable number of 


Johnny Billquist                  || "I'm on a bus
                                   ||  on a psychedelic trip
email: bqt@REDACTED             ||  Reading murder books
pdp is alive!                     ||  tryin' to stay hip" - B. Idol

More information about the erlang-questions mailing list