Group Abstract Group Abstract

Message Boards Message Boards

0
|
6.6K Views
|
4 Replies
|
7 Total Likes
View groups...
Share
Share this post:

Map a function where some of its parmeters are in a list ?

Posted 10 years ago

Hello

I defined a function this way

(*  myfunction[{parm1_,parm2_},parm3_] := ......*)

And I would like to map it in order to get :

  {myfunction[{a1,a2},a3],myfunction[{b1,b2},b3]}

The best I achieved so far is

myfunction /@ {{{a1, a2}, a3}, { {b1, b2}, b3  }}
(* {myfunction[{{a1, a2}, a3}], myfun[{{b1, b2}, b3}]}   answer  *)

I have one pair brackets to much but if I remove if from the Map parameter list the code is incomplete.

 myfunction /@ {{a1, a2}, a3, {b1, b2}, b3}   (* not right *)

Is it possible to use it in a pure function such as :

  myfunction [{#1, #2}, #3] &
  myfunction[{#1}, #2] & (* alternative*)

If so what should follow the & in order to get as before

 {myfunction[{a1,a2},a3],myfunction[{b1,b2},b3]}

Thanks

POSTED BY: Jan Potocki
4 Replies

The basic difference is that Map[f,{{a},{b}}] wraps f around the curly braces, giving {f[{a}],f[{b}}, while Apply removes the braces: Apply[f,{{a},{b}},1] gives {f[a],f[b]}. You can nest Apply inside Map with the same result:

Map[Apply[f,#]&, {{a},{b}}]

or, with the infix notation

Map[f@@#&, {{a},{b}}]

or, even more cryptically,

f@@#&/@{{a},{b}}
POSTED BY: Gianluca Gorni

Perhaps what you want is Apply at level 1:

Apply[myfunction, {{{a1, a2}, a3}, {{b1, b2}, b3}}, 1]

which can be shortened to

myfunction @@@ {{{a1, a2}, a3}, {{b1, b2}, b3}}
POSTED BY: Gianluca Gorni
Posted 10 years ago

This form of Apply is indeed an answer to my question.

As I was taken aback that Map could not be used here (a limitation which is not hinted in the Help for that function) I eventually found a way to stick with Map: just redefine the function by adding a pair of curly brackets to its arguments. The body of the function stays unchanged.

myf[{{x_, y_}, t_}] := x + y + t;
myf /@ { {{1, 2}, 3}, {{4, 5}, 6}}  (* answer {6, 15} *)
POSTED BY: Jan Potocki

The Apply method is much more elegant, but it does not mean that you cannot apply Map:

Map[myfunction[#[[1]], #[[2]]] &, {{{a1, a2}, a3}, {{b1, b2}, b3}}]

or shorter

myfunction[#[[1]], #[[2]]] & /@ {{{a1, a2}, a3}, {{b1, b2}, b3}}

should work, too.

Cheers,

M.

POSTED BY: Marco Thiel
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard