Using Thread
:
list1 = {a, b, c};
list2 = {x, y, z};
Thread[If[Thread[#1 > #2], 1, 0] &[list1, list2]]
(* {If[a > x, 1, 0], If[b > y, 1, 0], If[c > z, 1, 0]} *)
SeedRandom[0];
Thread[If[Thread[#1 > #2], 1, 0] &[RandomReal[1, 10],
RandomReal[1, 10]]]
(* {1, 0, 0, 0, 1, 1, 0, 1, 0, 1} *)
The problem with the code
Thread[If[#1 > #2, 1, 0] &[list1, list2]]
is that, while "Thread[f[args]]
'threads' f
over any lists that appear in args
,"
there are no lists in the arguments of the code that Thread
is applied to. The code that Thread
receives is If[{a, b, c} > {x, y, z}, 1, 0]
.
If the goal is to thread a function f
over lists f[list1, list2]
, the standard ways are to use MapThread
or make the function Listable
:
Function[Null, If[#1 > #2, 1, 0], Listable][list1, list2]
(* {If[a > x, 1, 0], If[b > y, 1, 0], If[c > z, 1, 0]} *)
Generic operator:
thread[f_] := Function[Null, f[##], Listable];
thread[If[#1 > #2, 1, 0] &][list1, list2]
(* {If[a > x, 1, 0], If[b > y, 1, 0], If[c > z, 1, 0]} *)
Of course, MapThread
already does this, with a slightly different syntax:
MapThread[If[#1 > #2, 1, 0] &]@{list1, list2}
(* {If[a > x, 1, 0], If[b > y, 1, 0], If[c > z, 1, 0]} *)
While thread[f]
and MapThread[f]@*List
produce equivalent outputs, they are not identical computations, since Listable
and mapping are implemented in different ways.
Thread[If[#,1,0]]&@Thread[Greater[##]]&[list1,list2]
$\endgroup$Subtract[1, UnitStep[Subtract[list2, list1]]]
. Or you can useBoolEval
, which does this under the hood. $\endgroup$Thread
as requested:If[#1 > #2, 1, 0] &[list1, list2] //. f_?(MemberQ[_List]) :> Thread[f]
$\endgroup$