# Repeatedly apply a bivariate function with one argument running over a list

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

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


I can get the result if I do:

Apply[f,{{{g,a},b},c},{0,2}]


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

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

lst = {a, b, c, d};
Fold[f, g, {a, b, c, d}]
(* f[f[f[f[g, a], b], c], d] *)

• Fold. Thank you! – Zorawar Dec 8 '15 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]

• Oh nice. Thanks for the info! – Zorawar Dec 8 '15 at 16:20