Message Boards Message Boards


Creating f[a][b][c][d]

Posted 6 years ago
6 Replies
7 Total Likes

Say one has a function, f, and a list, {a,b,c,d}. And say that that it makes sense to construct


Which is the same as


I want to be able to do this with a single function that takes 2 arguments, f and {a,b,c,d}. If I call this function ArgumentApply it would act like this

ArgumentApply[f, {a, b, c, d}]

and give the above result:


Why would I want this? Here is one example which I needed to code recently. Say that f is, in fact, an Association containing Associations. Here is a very simple example with Associations down to the 4th level:

fAssociation =
 <|a ->
   <|b ->
     <|c -> 
       <|d -> \[Pi]

And then one has:


<|b -> <|c -> <|d -> [Pi]|>|>|>

<|c -> <|d -> \[Pi]|>|>
<|d -> \[Pi]|>

So one might want the function ArgumentApply to take care of all of these possibilties using, respectively,

ArgumentApply[fAssociation, {a}]

ArgumentApply[fAssociation, {a, b}]

ArgumentApply[fAssociation, {a, b, c}]

ArgumentApply[fAssociation, {a, b, c, d}]

Here is one approach that works specifically for Associations:

ArgumentApply[f_Association, list_List] :=
  Module[{ fun,  x},  
  fun = <|"a" -> x|>;
  Scan[(fun = fun[#]) &, {"a", Sequence @@ list}];
  fun /. x -> f

Andindeed it works:

ArgumentApply[fAssociation, {a, b, c}]
<|d -> \[Pi]|>
ArgumentApply[fAssociation, {a, b, c, d}]

The question is whether there is a simple approach in Mathematica using a basic function with a particular argument choice and which works both for Associations as well as any other function head f.

6 Replies

What about something like this?

In[1]:= Fold[Compose, f, {a, b, c, d}]

Out[1]= f[a][b][c][d]


Nice one, @Jose M. Martin-Garcia! Docs say Compose has been superseded by Composition but simple replacement of former by later in your code did not work. @Jose M. Martin-Garcia, @Christopher Carlson, do you know what would do the trick?

Composition indeed replaces much of what Compose does:

In[2]:= Compose[f1, f2, f3, f4, x] === Compose[Composition[f1, f2, f3, f4], x]

Out[2]= True

but you see that the actual application of the function is still needed at the end, via Compose. So there is a bit of Compose that is not really superseded by Composition, and it is precisely the bit that is needed in this case.

Dang! Jose beat me to it. :)

A version suggested by Toni Schindler:

Fold[#[#2] &, f, {a, b, c, d}]


Thanks everyone!

Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract