Services & Resources / Wolfram Forums
MathGroup Archive
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2005

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

Search the Archive

Zero or one

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

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}]

  MatchQ[{1,2, 3}, {1, optional[2], 3}]

  MatchQ[{1, 2, 2, 3}, {1, optional[2], 3}]

  MatchQ[{1, "foo", 3}, {1, optional[_String | _Integer], 3}]

  MatchQ[{1, "foo", "bar", 3}, {1, optional[_String | _Integer], 3}]

Generalizations over a sequence of expressions, or to count between
exactly m and n repetitions of an expression, are also possible.


  • 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