Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Suppose I wanted to write down a list of $p^2$, for $p$ a prime between $1$ and $20$. I would expect

Table[If[PrimeQ[k], k^2, Sequence[]], {k, 1, 20}]

to work. In fact, this produces,

{Null, 4, 9, Null, 25, Null, 49, Null, Null, Null, 121, Null, 169, Null, Null, Null, 289, Null, 361, Null}

Why does this happen, and is there a variant which does work the way I expect?

Of course, I can just do

Map[(#^2) &, Select[Range[20], PrimeQ]]

I don't have a real reason to avoid this, but it feels less readable to me.

UPDATE: Given the answers I'm seeing, I should point out that this is meant to be a toy example and the actual code involves boolean functions much messier than PrimeQ[], for which there is no analogue of Prime[] available. But Szabolcs answer is exactly what I was looking for, thanks!

share|improve this question
2  
Just in case you weren't already aware of the enhanced abilities of Table[]: Table[k^2, {k, Select[Range[20], PrimeQ]}] also works well. –  J. M. Nov 13 '12 at 22:22
add comment

3 Answers

up vote 12 down vote accepted

The short answer is that Sequence[] expands already inside the If[ ... ] because If does not have the SequenceHold attribute. If[False, <<something>>] (i.e. missing third argument) will evaluate to Null.

Just use

Table[If[PrimeQ[k], k^2, Unevaluated@Sequence[]], {k, 1, 20}]
share|improve this answer
4  
...or use the "vanishing function" variation: Table[If[PrimeQ[k], k^2, ## &[]], {k, 20}] –  J. M. Nov 13 '12 at 22:18
1  
@J.M. the vanishing function is very useful in specific circumstances but I personally find it less transparent than the alternatives. Also, it comes with a certain amount of overhead--here, for example, it's almost 50% slower than using Unevaluated@Sequence[]. –  Oleksandr R. Nov 14 '12 at 14:15
add comment

Is this more readable?

Select[Prime[Range[20]], # < 20 &]^2

Or probably even better would be

Prime[Range[PrimePi[20]]]^2
share|improve this answer
    
Or, perhaps, myfn2[x_?PrimeQ] := x^2; myfn2[x_] := Sequence[]; Table[myfn2@k, {k, 1, 20}] –  TomD Nov 14 '12 at 0:33
add comment

Szabolcs explained the why, just an example of something readable you can use instead:

Table[Prime[n]^2, {n, PrimePi[20]}]
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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