2
$\begingroup$

Suppose I have defined some function (This is arbitrary)

 F[alpha_,a_,b_,c_]:=List[alpha,a+b+c]

I want to apply this F for a given huge list of sets

 {{alpha1, {a1,b1,c1}}, {alpha2, {a2,b2,c2}}, {alpha3, {a3,b3,c3}}}

Of course, I can plug this individually, but is there any smart way of plugging these lists into the function $F$ defined above?

For example, I know,

   F /@ List[a, b, c]

produce

 {F[a], F[b], F[c]}

So my first trial was just

  F /@ {{alpha1, {a1, b1, c1}}, {alpha2, {a2, b2, c2}}, alpha3, {a3, b3, c3}}}

But this gives an extra list outside and inside for $\{a1,b1,c1\}$. i.e.,

 {F[{alpha1, {a1, b1, c1}}], F[{alpha2, {a2, b2, c2}}], F[{alpha3, {a3, b3, c3}}]}

How one can do it wisely?


My solution is given as follows :

 Map[F[#[[1]], Sequence@@#[[2]]] &, {alpha1, {a1, b1, c1}}, {alpha2, {a2, b2, 
c2}}, {alpha3, {a3, b3, c3}}}]

then it produces desired one

$\endgroup$
1
  • 3
    $\begingroup$ If you rewrite the function as F[{alpha_,{a_,b_,c_}}]:=List[alpha,a+b+c], you can simply map it over your list. $\endgroup$ May 19, 2023 at 10:56

2 Answers 2

4
$\begingroup$
F[alpha_, a_, b_, c_] := List[alpha, a + b + c]

Let's start with what you didn't ask: If you had:

y = {{alpha1, a1, b1, c1}, {alpha2, a2, b2, c2}, {alpha3, a3, b3, c3}}

F @@@ y

would give:

{{alpha1, a1 + b1 + c1}, {alpha2, a2 + b2 + c2}, {alpha3, a3 + b3 + c3}}

For the case in the OP with an extra set of braces:

x = {{alpha1, {a1, b1, c1}}, {alpha2, {a2, b2, c2}}, {alpha3, {a3, b3, c3}}}

F[#1, Sequence @@ #2] & @@@ x

would deliver the same result.

{{alpha1, a1 + b1 + c1}, {alpha2, a2 + b2 + c2}, {alpha3, a3 + b3 + c3}}


Another variation using operator forms, where I can Flatten the arguments first and then use Apply down the list.

Map[Apply[F]][Map[Flatten][x]]
$\endgroup$
3
  • $\begingroup$ .. which I now realize is close enough to your recent edit to count as plagiarism. $\endgroup$
    – Syed
    May 19, 2023 at 9:41
  • $\begingroup$ Thanks for the quick answer! Can you explain to me what is the difference for @, @@, @@@? As far as I know @@ is nothing but a replacement, i.e., Sequence@@List[a,b,c]=Sequence[a,b], and @ can be used with /@, Map function, but I am not sure about @@@ x which you used in the answer! $\endgroup$
    – phy_math
    May 19, 2023 at 9:47
  • 1
    $\begingroup$ Define: t = {{a}, {b}, {c}, {d}}; and then try: f@t, f /@ t, f @@ t and f @@@ t on it. To gain insight on how the @@ changes an expression, look at TreeForm. $\endgroup$
    – Syed
    May 19, 2023 at 10:00
2
$\begingroup$

Point-free style:

list = {{alpha1, {a1, b1, c1}}, {alpha2, {a2, b2, c2}}, {alpha3, {a3, b3, c3}}};
Apply[F]@*Flatten /@ list
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.