Often when I'm writing OOP code using an object-manager association I find myself doing something akin to currying the arguments to some form of delegate object or head. (Building a one-argument chained call as opposed to returning functions of one argument).
Usually I do this via a Block construct but it is the sort of simple functional programming thing that Mathematica really ought to have a built-in for.
What I mean is I have something like:
c[a1, a2, a3, ..., an]
And I would like a function PseudoCurry that upon application to the previous expression would give me:
c[a1][a2][a3][...][an]
To my deep surprise I have been unable to find such a function.
Does anyone know how I can write a one-line, functional way to do this?
I'm sure the answer is dead simple but I'm blanking on it right now.
Update
Thanks to both Bob Hanlon and Mr. Wizard for the answers.
I think this from Bob:
Pseudocurry[h_[a__]] := Fold[#1[#2] &, {h, a}];
Pseudocurry~SetAttributes~HoldFirst;
is the cleanest way to do this without using deprecated functions but Mr. Wizard's
Pseudocurry[h_[a__]] := HeadCompose[h, a];
Pseudocurry~SetAttributes~HoldFirst;
is the clear winner for simplicity, although HeadCompose
is deprecated.
Answer
EDIT: Modified to cover situation when an argument is a List
Use Fold
expr = c[a1, a2, a3, a4, a5];
Fold[#1[#2] &, {c, List @@ expr} // Flatten[#, 1]&]
(* c[a1][a2][a3][a4][a5] *)
expr2 = c[a1, a2, {a31, a32, a33}, a4, a5];
Fold[#1[#2] &, {c, List @@ expr2} // Flatten[#, 1] &]
(* c[a1][a2][{a31, a32, a33}][a4][a5] *)
Comments
Post a Comment