# Applying And to a list inside a Function

And has HoldAll attribute and test its argument by sequence. But doing And@@{} will lost this advantage and slow down the code. Now I have a pure function

And @@ (PrimeQ[# + {1, 3, 7, 9, 13, 27}]) &


and I want it expand to

PrimeQ[# + 1] && PrimeQ[# + 3] && PrimeQ[# + 7] && PrimeQ[# + 9] &&
PrimeQ[# + 13] && PrimeQ[# + 27] &


to make use of the property of And. Currently I have

Evaluate[And @@
Function[u, h[u], Listable][# + {1, 3, 7, 9, 13, 27}]] & /.
h -> PrimeQ


But it looks counter intuitive. Are there better ways to do this?

• Look at AllTrue and see if it is to your liking. Aug 22, 2016 at 14:41
• Using AllTrue : AllTrue[# + {1, 3, 7, 9, 13, 27}, PrimeQ] & Aug 22, 2016 at 15:18
• Thanks rcollyer and JHM it worked for this case, but I also want to know what I should do when generally it is a list Aug 22, 2016 at 15:19
• You could do something like: AllTrue[Outer[Plus, #, {1, 3, 7, 9, 13, 27}], PrimeQ, 2] & Aug 22, 2016 at 22:51

For the exact expansion that you show:

Replace[And[1, 3, 7, 9, 13, 27] &, x_ :> PrimeQ[# + x], {2}]

PrimeQ[#1 + 1] && PrimeQ[#1 + 3] && PrimeQ[#1 + 7] &&
PrimeQ[#1 + 9] && PrimeQ[#1 + 13] && PrimeQ[#1 + 27] &


Or if you have an external list:

list = {1, 3, 7, 9, 13, 27};

With[{a = list},
And @@@ Replace[a &, x_ :> PrimeQ[# + x], {2}]
]

PrimeQ[#1 + 1] && PrimeQ[#1 + 3] && PrimeQ[#1 + 7] &&
PrimeQ[#1 + 9] && PrimeQ[#1 + 13] && PrimeQ[#1 + 27] &


Other approaches:

And @@@ Function @@ {PrimeQ /@ Hold @@ (# + list)}

PrimeQ /@ Hold @@ (# + list) /. _[x__] :> (And[x] &)


If sequential evaluation by other means is acceptable then also consider:

x \[Function] PrimeQ[x + #] & /@ And[1, 3, 7, 9, 13, 27];


As noted in the comments AllTrue, introduced in v10.0, provides a clean approach:

AllTrue[# + {1, 3, 7, 9, 13, 27}, PrimeQ] &    (* JungHwan Min *)


If you wish to prevent even the summation before testing:

x \[Function] AllTrue[{1, 3, 7, 9, 13, 27}, PrimeQ[x + #] &]