Re: Zero or one
- To: mathgroup at smc.vnet.net
- Subject: [mg62990] Re: Zero or one
- From: "dkr" <dkrjeg at adelphia.net>
- Date: Sat, 10 Dec 2005 06:02:59 -0500 (EST)
- References: <200512060503.AAA02671@smc.vnet.net><dn5oan$nj4$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
The following definitions are not equivalent:
In[1]:=
optional1[expr_] := expr | ___ ? (Length[{#}] == 0&);
optional2[expr_]:=expr|___?(#==Null&);
In[3]:=
MatchQ[{1,,3},{1,optional1[2],3}]
Out[3]=
False
In[4]:=
MatchQ[{1,,3},{1,optional2[2],3}]
Out[4]=
True
Some alternatives to optional1 are:
In[5]:=
optionalAlt1[expr_]:=expr|___?(!MatchQ[#,_]&);
optionalAlt2[expr_]:=expr|(a___/;!MatchQ[{a},{__}]);
In[7]:=
{MatchQ[{1,3},{1,#[2],3}],MatchQ[{1,2,3},{1,#[2],3}],
MatchQ[{1,2,2,3},{1,#[2],3}],
MatchQ[{1,"foo",3},{1,#[_String|_Integer],3}],
MatchQ[{1,"foo","bar",3},{1,#[_String|_Integer],3}],
MatchQ[{1,,3},{1,#[2],3}]}&/@{optionalAlt1,optionalAlt2,optional1}
Out[7]=
{{True,True,False,True,False,False},{True,True,False,True,False,False},{True,
True,False,True,False,False}}
In optionalAlt1, the pattern test rules out all non null sequences. If
the sequence is the null sequence, then the pattern test is ignored, as
evidenced by the following:
In[8]:=
MatchQ[{},{___?(False&)}]
Out[8]=
True
dkr
- Follow-Ups:
- Re: Re: Zero or one
- From: Andrzej Kozlowski <akoz@mimuw.edu.pl>
- Re: Re: Zero or one
- References:
- Zero or one
- From: "Trevor Baca" <trevorbaca@Gmail.com>
- Zero or one