In the meantime I'm accustomed to write special character orgies like D[%,#]&/@L
(to quickly fish out the coefficients of the last input with respect to the variables in list L - but I don't have to tell you that :-), but this here mixes Slot
and Map
. I have to lists L1
and L2
(of equal length 40). The function f
shall replace the k-th element of L1
with that of L2
. I could simply write f[z_]:=z/.Table[L1[[i]]->L2[[i]],{i,1,40}]
but I never become a MATHEMATICA genius that way :-) So f[z_]:=z/.(Rule[#1,#2]/@[L1,L2])
...nope, Slot doesn't work this way...
0
$\begingroup$
$\endgroup$
2
$\begingroup$
$\endgroup$
Clear[a, b, c, d, f]
l1 = {a, b}
l2 = {c, d}
rules = Thread[Rule[l1, l2]]
f[z_] := z /. rules
f[a x + b] (* d + c x *)
2
$\begingroup$
$\endgroup$
I'm assuming you're simply looking for a way to mimic what Table[L1[[i]] -> L2[[i]], {i, 1, 40}]
does. Here are some possibilities:
L1 = Range[40];
L2 = 2 L1;
out1 = Table[L1[[i]] -> L2[[i]], {i, 1, 40}]
out2 = Thread[L1 -> L2]
out3 = MapThread[Rule, {L1, L2}]
out4 = Inner[Rule, L1, L2, List]
out5 = Rule @@@ Transpose[{L1, L2}]
out6 = Apply[Rule] /@ Transpose[{L1, L2}]
out1 === out2 === out3 === out4 === out5 === out6
(*True*)
edit
I just thought of another one:
out7 = Function[{x, y}, x -> y, Listable][L1, L2]
out7 === out1
(*True*)
-
$\begingroup$ Ah, Thread was the operator I looked for. It's sort of an argument-Map, right? Accepted for the multitude of cool curry :-) $\endgroup$ – Hauke Reddmann May 23 '18 at 19:03
-
$\begingroup$ I always think of
Thread
as a function that "pulls" lists out wherever possible (thus creating a single list of an expression that contains multiple lists). Though it's not limited to just lists: for example, you can reverse the possess again withThread[out2, Rule]
, in which case it "pulls" theRule
outside. $\endgroup$ – Sjoerd Smit May 23 '18 at 20:27
f[z_] := z /. (Rule[#[[1]], #[[2]]] & /@ Transpose[{L1, L2}])
orf[z_] := z /. Rule @@@ Transpose[{L1, L2}]
? $\endgroup$ – kglr May 23 '18 at 13:24