MathGroup Archive 2005

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

Search the Archive

Zero or one

  • To: mathgroup at smc.vnet.net
  • Subject: [mg62813] Zero or one
  • From: "Trevor Baca" <trevorbaca at Gmail.com>
  • Date: Tue, 6 Dec 2005 00:03:09 -0500 (EST)
  • Sender: owner-wri-mathgroup at wolfram.com

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.


  • Prev by Date: Re: How to set up a diff equation for circuit with a diode?
  • Next by Date: Re: Threading 'Append'
  • Previous by thread: [JLINK] passing a function reference
  • Next by thread: Re: Zero or one