MathGroup Archive 2005

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Zero or one


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


  • Prev by Date: functional programming
  • Next by Date: Re: Solve Limitations
  • Previous by thread: Re: Zero or one
  • Next by thread: Re: Re: Zero or one