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

Posted 6 years ago
5959 Views
|
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 f[a][b][c][d] Which is the same as (((f[a])[b])[c])[d] 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: f[a][b][c][d] 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: fAssociation[a]  <|b -> <|c -> <|d -> [Pi]|>|>|> fAssociation[a][b]  <|c -> <|d -> \[Pi]|>|>  fAssociation[a][b][c]  <|d -> \[Pi]|>  fAssociation[a][b][c][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}]  \[Pi]  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
Sort By:
Posted 6 years ago
 What about something like this?In[1]:= Fold[Compose, f, {a, b, c, d}]Out[1]= f[a][b][c][d]Jose.
Posted 6 years ago
 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?
Posted 6 years ago
 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]= Truebut 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.
Posted 6 years ago
 Dang! Jose beat me to it. :)
 A version suggested by Toni Schindler: Fold[#[#2] &, f, {a, b, c, d}]  f[a][b][c][d]