MathGroup Archive 2007

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

Search the Archive

Re: Pattern test and expression sequence

Jan Lellmann wrote:
> Hello,
> I want to define a pattern that accepts a sequence of expressions (of 
> arbitrary length) that matches some condition. So as a minimalist 
> example, if I wanted to accept all expressions with f as head and at 
> least 2 arguments, I want to write
> myQ[x__] := (Print[x]; Length[{x}] > 1)
> f[x__?myQ] := works[x];
> f[1, 2]
> This should print "1 2" and return "works[1,2]". But it doesn't, it just 
> prints "1" and returns f[1,2] unevaluated. So apparenty Mathematica does 
> not pass the complete expression sequence to myQ, but only the first 
> element ("1").

This is because x__?myQ only matches if myQ gives True for each argument 
separately, i.e.\ in this case f[1,2] evaluates only if both myQ[1] and 
myQ[2] are True.

> There is a workaround using /; :
> f[x__] /; (myQ[x] == True) := works[x];
> but it is rather ugly and cumbersome when there is more than one argument.

Why do you find it uglier than using '?' ?  You could simply write

f[x__] /; myQ[x] := works[x]


f[x__] := works[x] /; myQ[x]


  • Prev by Date: Re: Mac OS X 10.5 - Mathematica 5.1 hangs - 6.0 works?
  • Next by Date: Question about RandomInteger
  • Previous by thread: Pattern test and expression sequence
  • Next by thread: Re: Pattern test and expression sequence