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...

  • $\begingroup$ Sorry, it's not clear to me if you want to assign just one user-defined element from L2 to L1 or if you want to do something else. $\endgroup$
    – Fraccalo
    May 23, 2018 at 13:14
  • $\begingroup$ you mean f[z_] := z /. (Rule[#[[1]], #[[2]]] & /@ Transpose[{L1, L2}]) or f[z_] := z /. Rule @@@ Transpose[{L1, L2}]? $\endgroup$
    – kglr
    May 23, 2018 at 13:24
  • $\begingroup$ Could you please clarify the desired input and output with an example? As it stands, I'm afraid that I can't understand what you need. $\endgroup$
    – MarcoB
    May 23, 2018 at 14:24

2 Answers 2

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 *)

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


I just thought of another one:

out7 = Function[{x, y}, x -> y, Listable][L1, L2]
out7 === out1
  • $\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$ May 23, 2018 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 with Thread[out2, Rule], in which case it "pulls" the Rule outside. $\endgroup$ May 23, 2018 at 20:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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