7
$\begingroup$

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?

$\endgroup$
4
  • 2
    $\begingroup$ Look at AllTrue and see if it is to your liking. $\endgroup$
    – rcollyer
    Aug 22, 2016 at 14:41
  • $\begingroup$ Using AllTrue : AllTrue[# + {1, 3, 7, 9, 13, 27}, PrimeQ] & $\endgroup$ Aug 22, 2016 at 15:18
  • $\begingroup$ 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 $\endgroup$
    – vapor
    Aug 22, 2016 at 15:19
  • $\begingroup$ You could do something like: AllTrue[Outer[Plus, #, {1, 3, 7, 9, 13, 27}], PrimeQ, 2] & $\endgroup$ Aug 22, 2016 at 22:51

1 Answer 1

3
$\begingroup$

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 + #] &]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.