2
$\begingroup$

I have a function that returns an expression in the form f[{a,b}], and I use this function twice and assemble the expression {f[{a,b}],f[{c,d}]}. I wish to apply a function g to corresponding arguments and zip that up with the original head f.

To specify my use case, f is Row[] and {a,b} and {c,d} lists of Plots. I want to Show corresponding plots together and zip that result up within Row again.

My question is Does this already exist? and if not How to nicely implement it?

$\endgroup$

2 Answers 2

2
$\begingroup$

I came up with this solution:

zip[fun_,exprs_List]:=First[Head/@exprs][Map[fun,Transpose[Flatten[List@@@exprs,1]]]]/;Length[Union[Head/@exprs]]==1

p1 = Plot[Sin[x], {x, 0, Pi}];
p2 = Plot[Cos[x], {x, 0, Pi}];
p3 = Plot[Tan[x], {x, 0, Pi/2}];
p4 = Plot[Csc[x], {x, 0.1, Pi}];
p5 = Plot[Sec[x], {x, 0, Pi}];
p6 = Plot[Cot[x], {x, 0.1, Pi}];

r1 = Row[{p1, p2, p3}];
r2 = Row[{p4, p5, p6}];


zip[Show, {r1, r2}]

Did i reinvent the wheel?

$\endgroup$
2
$\begingroup$

I can't recall one single built-in function for the task, but here's a simpler solution for your specific task:

p1 = Plot[Sin[x], {x, 0, Pi}];
p2 = Plot[Cos[x], {x, 0, Pi}];
p3 = Plot[Tan[x], {x, 0, Pi/2}];
p4 = Plot[Csc[x], {x, 0.1, Pi}];
p5 = Plot[Sec[x], {x, 0, Pi}];
p6 = Plot[Cot[x], {x, 0.1, Pi}];

r1 = Row[{p1, p2, p3}];
r2 = Row[{p4, p5, p6}];

Clear@show;
show[a__List] := MapThread[Show, {a}]

Thread[show[r1, r2], Row]

Based on the same idea, a generalized zip function can be defined as:

Clear@zip;
zip[g_, {expr : f_[__] ..}] :=
 Module[{func},
  func[a__List] := MapThread[g[{##}] &, {a}];
  Thread[func[expr], f]]

zip[g, {f[{a, b}], f[{c, d}]}]
(* f[{g[{a, c}], g[{b, d}]}] *)
$\endgroup$

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.