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.
- Follow-Ups:
- Re: Zero or one
- From: Andrzej Kozlowski <akoz@mimuw.edu.pl>
- Re: Zero or one