MathGroup Archive 2005

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

Search the Archive

Re: Zero or one

  • To: mathgroup at smc.vnet.net
  • Subject: [mg62862] Re: [mg62813] Zero or one
  • From: Andrzej Kozlowski <akoz at mimuw.edu.pl>
  • Date: Tue, 6 Dec 2005 23:10:58 -0500 (EST)
  • References: <200512060503.AAA02671@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

On 6 Dec 2005, at 14:03, Trevor Baca wrote:

> Matching "zero or one" of something is helpful sometimes. String
> patterns have the usual ? regex, but _, __ and ___ aren't quite the
> same for function definitions and MatchQ[ ]. For these occasions,
> there's the following bit of syntactic sugar.
>
> The pattern
>
>   ___ ? (Length[{#}] == 0&)
>
> is one way to say "zero of something". Wrapped into a function, we get
> something like
>
>   optional[expr_] := expr | ___ ? (Length[{#}] == 0&);
>
> as a way of saying "zero or one of expr". Examples:
>
>   MatchQ[{1,3}, {1, optional[2], 3}]
>   True
>
>   MatchQ[{1,2, 3}, {1, optional[2], 3}]
>   True
>
>   MatchQ[{1, 2, 2, 3}, {1, optional[2], 3}]
>   False
>
>   MatchQ[{1, "foo", 3}, {1, optional[_String | _Integer], 3}]
>   True
>
>   MatchQ[{1, "foo", "bar", 3}, {1, optional[_String | _Integer], 3}]
>   False
>
> Generalizations over a sequence of expressions, or to count between
> exactly m and n repetitions of an expression, are also possible.
>
> Trevor.
>

A nice idea. It may be a little more direct to define optional by:

optional[expr_] := expr | ___? (#==Null&);

Andrzej Kozlowski


  • References:
    • Zero or one
      • From: "Trevor Baca" <trevorbaca@Gmail.com>
  • Prev by Date: Re: Types in Mathematica thread
  • Next by Date: Re: Re: Types in Mathematica, a practical example
  • Previous by thread: Zero or one
  • Next by thread: Re: Zero or one