New answers tagged map
3
You have already seen that there are a number of ways to skin this cat but I'd like to add some comments of my own.
Other approaches
When possible I prefer to avoid these situations in the first place, instead using something like:
{{1, 2}, {3, 4}, {5, 6}} /. {x_, y_} :> Thread@{x, {y, y^2, y^3}} // Thread
{{{1, 2}, {3, 4}, {5, 6}}, {{1, 4}, {3, ...
3
I'll just aggregrate here the various responses from the comments, plus my own humble thoughts and understanding (which may lack precision or contain mistakes, so feel free to improve or correct):
Be careful about variable naming. (This is assuming that, generally speaking, you have good reason to have global variables spilling out in your program.)
Use ...
4
As expressed in the comments, the Replace functions are not merely "syntactic sugar" for Map. The two are quite different. One primary difference is the order in which expressions are visited. See:
How to perform a depth-first preorder traversal of an expression?
Another is that Replace will go inside held expressions, while Map does not evaluate:
Hold[1 ...
6
For educational purposes, here's a couple other ways to do this:
Power @@@ {{1, 2}, {2, 2}, {3, 2}}
Power[Sequence @@ #] & /@ {{1, 2}, {2, 2}, {3, 2}}
Cases[{{1, 2}, {2, 2}, {3, 2}}, List[x__] :> Power[x]]
# /. List -> Power & /@ {{1, 2}, {2, 2}, {3, 2}}
Replace[{{1, 2}, {2, 2}, {3, 2}}, List -> Power, {2}, Heads -> True]
...
8
First of all, let's clarify that if you define h as
`h[{x_, y_}] := ...`
then it takes a single argument which is a list of two items. If you define it as
`h[x_, y_] := ...`
then it takes two separate arguments.
#n denotes the nth argument in a pure function. In the function call (#1^#2)& [{2,3}] you are passing the pure function a single ...
6
If you want to use Map[] that is possible too:
#[[1]]^#[[2]] & /@ {{1, 2}, {2, 2}, {3, 2}}
3
You should use Apply (at the level 1 (@@@)) rather than Map, in terms of a pure function as you looking for:
#1^#2 & @@@ {{1, 2}, {2, 2}, {3, 2}}
{1, 4, 9}
Instead of a pure function #1^#2 & one can simply write built-in Power.
Your h function takes only one argument i.e. a two-element list, while the second one (a pure function) has two ...
5
But it doesn't work. Why is that?
It becomes visible when you inspect the inner Map only. I replace the slot for the outer function with 1, because we don't need it to see the error
b = {1, 2};
c = {1, 2, 3};
Map[f[# &, 1], b]
(* {f[#1 &, 1][1], f[#1 &, 1][2]} *)
This is not what you expect and when you look a bit closer, you instantly ...
Top 50 recent answers are included

