MathGroup Archive 2004

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

Search the Archive

Re: An argument pattern problem: ranges and lists

  • To: mathgroup at smc.vnet.net
  • Subject: [mg53001] Re: An argument pattern problem: ranges and lists
  • From: David Bailey <dave at Remove_Thisdbailey.co.uk>
  • Date: Sun, 19 Dec 2004 06:14:48 -0500 (EST)
  • References: <cq0tro$2n8$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

Simon Anders wrote:
> Hi,
> 
> I am trying to use argument patterns to ensure that my function is only 
> applied onto arguments which have the format
>     pauli [_, _]
> where the second argument should be an integer between 0 and 4.
> 
> So I defined a type
>     pauliT = HoldPattern [pauli [_, s_Integer] /; s>=0 && s<=4];
> 
> and declared my function as follows:
>    f [p:pauliT] := DoSomething
> 
> This works fine, but another function takes a pair of arguments
>    g [p:{pauliT,pauliT}] := DoSomethingElse
> 
> This is never called, because the pattern cannot be matched.
> 
> I observed:
> 
>    pauliT = HoldPattern [pauli [_, s_Integer] /; s>=0 && s<=4];
>    MatchQ[{pauli[1, 2], pauli[1, 3]}, {pauliT, pauliT}]
>    --> False
> 
> The problem seems to be that I named the second argument 's', because if 
> I delete this name, it matches:
> 
>    pauliT = HoldPattern [pauli [_, s_Integer]];
>    MatchQ[{pauli[1, 2], pauli[1, 3]}, {pauliT, pauliT}]
>    --> False
> 
>    pauliT = HoldPattern [pauli [_, _Integer]];
>    MatchQ[{pauli[1, 2], pauli[1, 3]}, {pauliT, pauliT}]
>    --> True
> 
> So, how do I specify the range condition correctly?
> 
> Thanks in advance,
>    Simon
> 
> 
> 
Hi Simon,

I like your style in defining variables to contain patterns, however if 
you think about what happens if you have a repeated copy of pauliT, you 
end up with the same named pattern occurring twice - so the rules of 
Mathematica specify that it must match the same thing. You need to get a 
unique variable (rather than s) each time you use pauiliT. This can be 
done using 'With' after allowing for the subtlety that 'With'
handles /; constructs specially:

pauliT := With[{s = Unique[]},
       HoldPattern[Condition1[pauli[_, s_Integer], (s > 0 && s <= 4)]]
                  ] /. Condition1 -> Condition;

Of course, in this case it would be easier to avoid using a pattern 
variable and write:

pauliT = HoldPattern[pauli[_, 1 | 2 | 3 | 4]]

David Bailey
dbaileyconsultancy.co.uk


  • Prev by Date: Re: Mathematica language issues
  • Next by Date: Re: Re: Mathematica slows down
  • Previous by thread: Re: An argument pattern problem: ranges and lists
  • Next by thread: Using NMinimize to solve a system of equations