Tag Info

Hot answers tagged

10

Interesting question. Here is my proposal: fn[f_, expr_] := Module[{h}, h[x_List, _] := x; h[o_[x__h], i_] := h[o @@ {x}[[All, 1]], i]; MapIndexed[h, expr, {1, -1}] /. h -> f ] Test: fn[h, {a, q Sqrt[r], {{{e + f g h}, c^d}, b}}] {h[a, {1}], h[q Sqrt[r], {2}], {{{h[e + f g h, {3, 1, 1, 1}]}, h[c^d, {3, 1, 2}]}, h[b, {3, 2}]}} I ...


9

What you have is a so called linked list, and such lists are usually traversed through recursion like this: applyFunc[f_, {el_, rest_}, level_: {1}] := {f[el, level], applyFunc[f, rest, Prepend[level, 2]]} applyFunc[f_, {el_}, level_] := {f[el, level]} applyFunc[h, expr] {h[a, {1}], {h[b, {2, 1}], {h[c^d, {2, 2, 1}], {h[e + f g, {2, 2, 2,1}]}}}} But ...


8

May be this is not the smarter way to do it but here is what I got: l = {a, {b, {c^d, {e + f g}}}}; pos = ReplaceAll[(Position[l, List]), 0 -> 1]; h[l[[Sequence @@ #]], #] & /@ pos (*{h[a, {1}], h[b, {2, 1}], h[c^d, {2, 2, 1}], h[e + f g, {2, 2, 2, 1}]}*) If you want to keep the levels as they are then: rule = Rule[#, h[l[[Sequence @@ #]], #]] ...


5

Update Well I guess I should retire for the evening to a less brain-intensive activity as apparently I can't think clearly. One could of course use Outer: Outer[Compose, {f, g}, {a, b, c}] {{f[a], f[b], f[c]}, {g[a], g[b], g[c]}} However I recommend that you do not do this as you will not gain the auto-compilation of Map, meaning this method will ...


5

ReplacePart If one is willing to bend on the requirement to use MapIndexed, ReplacePart can generate the desired output directly: $list = {a, {b, {c^d, {e + f g}}}}; ReplacePart[$list, {i:PatternSequence[2..., 1]} :> h[$list[[i]], {i}]] (* {h[a, {1}], {h[b, {2, 1}], {h[c^d, {2, 2, 1}], {h[e + f g, {2, 2, 2, 1}]}}}} *) MapIndexed Alternatively, we ...


4

I don't think there's any built-in function to do this, but here is an alternative: myFunc[func_, data_] := Transpose[Through[func[#]] & /@ data] Then myFunc[{f, g, h}, {a, b, c}] {{f[a], f[b], f[c]}, {g[a], g[b], g[c]}, {h[a], h[b], h[c]}}



Only top voted, non community-wiki answers of a minimum length are eligible