8
$\begingroup$

Happy new year, everyone! I hope this is a good one.

The title doesn't really express well what I want to do, however, please see further explenation below.

Say, I have a list of functions flist - {f,g,h} where function f takes three arguments; function g takes six arguments; and function h takes four arguments. Furthermore, I have an argument list alist with randomly generated numbers which will serve as an input to the above functions.

How could I apply argument list alist to flist in such a way where each function in flist would take appropriate subset of elements from alist; whilst ensuring functions in flist do not share elements from alist.

Example

flist = {f,g,h};
alist = {1,2,3,4,5,6,7,8,9,10,11,12,13};

~magic~ 

f[1,2,3]
g[4,5,6,7,8,9]
h[10,11,12,13]

I know I could do something like

f @@ alist[[;;3]]
g @@ alist[[4;;9]]
h @@ alist[[10;;13]]

This said, I was wondering if there is a better way to do it. A more ~lazy~ approach.

$\endgroup$

1 Answer 1

14
$\begingroup$
 MapThread[Apply] @ {flist, TakeList[alist, {3, 6, 4}]}

f[1, 2, 3], g[4, 5, 6, 7, 8, 9], h[10, 11, 12, 13]}

Also

MapThread[# @@ #2 &] @ {flist, TakeList[alist, {3, 6, 4}]}

{f[1, 2, 3], g[4, 5, 6, 7, 8, 9], h[10, 11, 12, 13]}

Update: If TakeList is not available in your version, you can use Internal`PartitionRagged or FoldPairList + TakeDrop:

Internal`PartitionRagged[alist, {3, 6, 4}] == 
 FoldPairList[TakeDrop, alist, {3, 6, 4}] == 
  TakeList[alist, {3, 6, 4}]

True

$\endgroup$
2
  • $\begingroup$ how would you implement above in Mathematica version 11.0.1.0? Unfortunately, I do not have TakeList function available :s $\endgroup$ Jan 14, 2020 at 16:20
  • 1
    $\begingroup$ @e.doroskevic, please see the update. $\endgroup$
    – kglr
    Jan 14, 2020 at 16:26

Your Answer

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

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