Re: Match exactly zero or one
- To: mathgroup at smc.vnet.net
- Subject: [mg60538] Re: Match exactly zero or one
- From: Peter Pein <petsie at dordos.net>
- Date: Tue, 20 Sep 2005 05:18:53 -0400 (EDT)
- References: <dgm0ef$npn$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Trevor Baca schrieb:
> What's the easiest way to match exactly zero or one expressions within,
> say, MatchQ[ ]?
>
> For example: call any expression expr a well-formed foo when and only
> when (1) the head of expr equals foo; (2) the first element of expr is
> either 0 or 1 bar expressions; (3) the last element of expr is an
> integer. Then neither the predicate ...
>
> FooQ[expr_] := MatchQ[expr, foo[_bar, _Integer]]
>
> .... nor ...
>
> FooQ[expr_] := MatchQ[expr, foo[__bar, _Integer]]
>
> .... nor ...
>
> FooQ[expr_] := MatchQ[expr, foo[___bar, _Integer]]
>
> .... accurately capture the definition of foo.
>
> For string-matching there's the ? operator; but what's the best
> approach for expression-matching?
>
> (FWIW Gavin Scott posed this question in December 2000, but I couldn't
> find an answer in the thread.)
>
>
> Trevor.
>
Hi Trevor,
using named patterns:
In[1]:=
FooQ[expr_] :=
MatchQ[expr, foo[bbq___bar /; Length[{bbq}] <= 1, _Integer]]
In[2]:= FooQ[foo[bar[this], 5]]
Out[2]= True
In[3]:= FooQ[foo[Pi]]
Out[3]= False
In[4]:= FooQ[foo[Floor[Pi]]]
Out[4]= True
In[5]:= FooQ[foo[bar[this], bar[that], 13]]
Out[5]= False
is this correct?
--
Peter Pein, Berlin
GnuPG Key ID: 0xA34C5A82
http://people.freenet.de/Peter_Berlin/