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

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