Re: multiple variables in pure function used in map.
- To: mathgroup at smc.vnet.net
- Subject: [mg107640] Re: multiple variables in pure function used in map.
- From: Raffy <adraffy at gmail.com>
- Date: Sun, 21 Feb 2010 04:24:00 -0500 (EST)
- References: <hlohjt$d95$1@smc.vnet.net>
On Feb 20, 3:38 am, pipehappy <pipeha... at gmail.com> wrote:
> Hi, All
>
> Is there a way to use multiple variables in pure function with map.
>
> What I want to do is like this:
>
> ab = {{1, 2}, {2, 3}, {3, 4}};
> (#[[1]] + #[[2]]) & /@ ab
> {3, 5, 7}
>
> Instead of refer to elements in list I want to use multiple variables
> in pure function.
>
> something like this:
> ab = {{1, 2}, {2, 3}, {3, 4}};
> (#1 + #2) & /@ ab
> To do the same thing as the above example.
>
> Best
>
> -- pipehappy
Apply (at level 1) is what you need.
Recall, FullForm of {{1,2}, {3,4}} is List[List[1,2], List[3,4]]
Apply[h, ex, level] replaces the head of each expression at level of
ex with h.
So, Apply[func, List[List[1,2], List[3,4]], {1}] will give you
List[func[1,2], func[3,4]].
The shorthand for Apply at level {1} is @@@.
#1+#2&@@@{{1,2},{3,4}}
However, this is just Plus@@@{{1,2},{3,4}}, or better: Total[{{1,2},
{3,4}},{2}].