I'd like to know how, given symbols f and g, and a list {a,b,c,...}, to produce the expression:


I can get the result if I do:


but then how do I manipulate the list {a,b,c} into {{{g,a},b},c}? Is there a better way of doing it?

  • $\begingroup$ Possible duplicates?: (7924), (25474). (Do we really have so simpler questions dealing with Fold?) $\endgroup$
    – Mr.Wizard
    Jan 29, 2016 at 22:12

2 Answers 2

lst = {a, b, c, d};
Fold[f, g, {a, b, c, d}]
(* f[f[f[f[g, a], b], c], d] *)
  • $\begingroup$ Fold. Thank you! $\endgroup$
    – Zorawar
    Dec 8, 2015 at 3:34

Don't do this at home; use bbgodfrey's solution. :-)

However, Fold is also the answer to your question on how to transform {a, b, c, d, e} into {{{{{g, a}, b}, c}, d}, e}. But you don't have follow with a fancy application of Apply; a simple substitution is all you need.

data = {a, b, c, d, e};
tmp = Fold[List, g, data]

{{{{{g, a}, b}, c}, d}, e}

tmp /. List -> f

f[f[f[f[f[g, a], b], c], d], e]

  • $\begingroup$ Oh nice. Thanks for the info! $\endgroup$
    – Zorawar
    Dec 8, 2015 at 16:20

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.