It's sad to see a question about Thread
sidestep the discussion about Thread
so I'll try to fill in the void, though it is becoming redundant after Simon's answer.
The normal sequence of evaluation for something like f[a, b, c]
is to evaluate a
, b
, and c
first (let's say, they are 5, 1, and 2, respectively). So then we get f[5, 1, 2]
. And then Mathematica evaluates that if it has a rule set up for it. Thread
is no exception.
As in the OP:
findPrime[n_] := If[PrimeQ[n], i = 1; While[Prime[i] < n, i = i + 1]; i, False];
Therefore:
Thread[findPrime[{7,8,37,127}]]
evaluates to
Thread[
If[PrimeQ[{7,8,37,127}], i = 1; While[Prime[i] < {7,8,37,127}, i = i + 1]; i, False];
]
wherein PrimeQ[{7,8,37,127}]
evaluates to {True,False,True,True}
, after which we have
Thread[
If[{True,False,True,True}, i = 1; While[Prime[i] < {7,8,37,127}, i = i + 1]; i, False];
]
Finally we reach a point where Mathematica doesn't know what to do next, so it threads If
over the first argument, while the other two arguments are the same for each case. Also, because Prime[i] < {7,8,37,127}
cannot be evaluated as true or false, the While
loop does not work any cycles. So after thread operates we get
{
If[True, i = 1; i, False];,
If[False, i = 1; i, False];,
If[True, i = 1; i, False];,
If[True, i = 1; i, False];,
}
That's why Simon suggested to restrict the input to findPrime
. If findPrime
were to accept only integers as arguments and not do anything if given other types of arguments, such as list,
Thread[findPrime[{7,8,37,127}]]
would have no chance of prematurely evaluating the argument of Thread
, so the only thing to do would be to go right ahead and convert to
{findPrime[7], findPrime[8], findPrime[37], findPrime[127]}
To address the other question:
Also Thread[f[{a,b,c},x,{d,e,f}]]
evaluates to {f[a,x,d],f[b,x,e],f[c,x,f]}
, let's see you do that with Map
or even MapThread
:-)
findPrime[{7,8,37,127}]
evaluates first, only then doesThread
act. Also, the capabilities ofThread
, though similar toMap
at first glance, are different and in your example one of those differences just bit you in the arse :-) You should check the documentation ofMapThread
, if it's not immediately clear how differentThread
is fromMap
. $\endgroup$PrimePi[]
? $\endgroup$Thread
). The second part (difference betweenThread
andMapThread
) is certainly covered in those, though. $\endgroup$