I was looking at this Q&A about using pattern test (pattern_?test
) vs pattern condition (pattern_/;cond
) and came across this example where using condition was the only possible way to restrict the function parameters (function definition added by me):
Clear[fCond]
fCond[x__ /; Plus[x] == 7] := {x}^2
fCond[1, 2, 4]
(* {1, 4, 16} *)
I know that, aside from the built-in tests in MMA (IntegerQ, NumericQ, eg), one can write custom pattern tests using pure functions [2]:
Hence, I was trying to be clever by using tests with sequence pattern (__) coupled with sequence argument for pure function (##). However, this did not work when plugging in values for the parameter/pattern.
Clear[fTest]
fTest[x__?(Plus[##] == 7 &)] := {x}^2
fTest[1, 2, 4]
(* fTest[1, 2, 4] *)
, even though the pure function test alone does work with the plugged in sequence
Plus[##] == 7 &[1, 2, 4]
(* True *)
Why doesn't pattern test work via this method? If so, is there any other way to do pattern test as opposed to pattern condition in this case?
[2]: Ruskeepaa's Mathematica Navigator 2009 p.498
__?test
the test is applied to each argument, not to the sequence as a whole. TryfTest[7, 7, 7]
. I have learned it from your previous question btw :) $\endgroup$