3

Often I will have a table with different mutations to the same value and I end up repeating the same expression multiple times. A simple example:

Grid[Table[{i*100 + 17, PrimeQ[i*100 + 17]}, {i, 0, 20}]]

So, in this example the expression i*100+17 is repeated twice, once to show what the value is, then a second time to compute whether the value is prime.

How can write the expression more economically so that the linear expression is used only once and not repeated?

Tyler Durden
  • 4,090
  • 14
  • 43
  • something like Grid[Table[{j = i*100 + 17, PrimeQ[j]}, {i, 0, 20}]]? – kglr Jan 27 '17 at 03:27
  • 2
    With[] and other scoping constructs are usable within Table[], you know... – J. M.'s missing motivation Jan 27 '17 at 03:33
  • There are many possibilities, but perhaps you're looking for something like: Table[{j,PrimeQ[j]},{j,Table[100i+17,{i,0,20}]}] or the simpler version Table[{j,PrimeQ[j]},{j,100 Range[0,20]+17}]. – Carl Woll Jan 27 '17 at 03:43
  • There is a duplicate I failed to find, even though I gave an answer there. But it is hard to find {#, #}& [1 +1]. – Kuba Jan 27 '17 at 07:39

1 Answers1

2

I do not feel that the existing answers are quite "safe" as shown.

m_goldberg's code does not localize i correctly, e.g.

i = "fail!";

Grid[With[{j = i 100 + 17}, Table[{j, PrimeQ[j]}, {i, 0, 20}]]]
17+100 fail!  False
17+100 fail!  False
17+100 fail!  False
. . .

This is subtle as normally i is localized by Table but here is it evaluated ouside Table. This could be improved by using the delayed form of With but note that the expression will be evaluated as many times as j appears which could be significant in some code.

Nasser's code has a similar problem in that j is not localized which could interfere with other code.

Solutions

Here are three methods that each scope properly. (Grid omitted for clarity.)

(* Function *)

Table[{#, PrimeQ[#]} &[i 100 + 17], {i, 0, 20}]


(* replacement - "injector pattern" *)

Table[i 100 + 17 /. j_ :> {j, PrimeQ[j]}, {i, 0, 20}]


(* Table dummy iterator *)

Table[{j, PrimeQ[j]}, {j, {i 100 + 17}}, {i, 0, 20}] // First
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371