another way to do this mapping of a two argument function
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 n
th argument in a pure function. In the function call (#1^#2)& [{2,3}]
you are passing the pure function a single argument. #2
won't have a value so you get an error. If you pass it two arguments, everything is fine: (#1^#2)& [2, 3]
Starting with a list of two items, such as {2,3}
, you can use Apply
to pass these two items to a function:
Apply[#1^#2 &, {2,3}]
An alternate notation for this is #1^#2 & @@ {2,3}
.
You can also Apply
at level 1
. Check the docs details.
Apply[f, {{1,2}, {3,4}, {4,5}}, {1}]
(* ==> {f[1,2], f[3,4], f[4,5]} *)
A shorthand for the above is f @@@ {{1,2}, {3,4}, {4,5}}
.
In conclusion, what you want is
#1^#2 & @@@ {{1,2}, {2,2}, {3,4}}
If you want to use Map[] that is possible too:
#[[1]]^#[[2]] & /@ {{1, 2}, {2, 2}, {3, 2}}
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]
Note that this kind of head replacement is essentially what @@@
is doing, though @@@
does it specifically at level 1.
MapThread[Power, Transpose[{{1, 2}, {2, 2}, {3, 2}}]]
Power itself threads over lists:
{bases, exponents} = Transpose[{{1, 2}, {2, 2}, {3, 2}}]
bases^exponents
Your functions aren't so awesome:
{bases, exponents} = Transpose[{{1, 2}, {2, 2}, {3, 2}}]
(op[#1, #2] &)[bases, exponents]
You can make them awesome, SetAttributes
method:
SetAttributes[f, Listable];
f[a_, b_] := op[a, b];
{bases, exponents} = Transpose[{{1, 2}, {2, 2}, {3, 2}}]
f[bases, exponents]
Thread
method:
{bases, exponents} = Transpose[{{1, 2}, {2, 2}, {3, 2}}]
Thread[(op[#1, #2] &)[bases, exponents]]
Third argument to Function
method:
{bases, exponents} = Transpose[{{1, 2}, {2, 2}, {3, 2}}]
Function[{a, b}, op[a, b], Listable][bases, exponents]