3

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?

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
Zorawar
  • 235
  • 1
  • 6

2 Answers2

6
lst = {a, b, c, d};
Fold[f, g, {a, b, c, d}]
(* f[f[f[f[g, a], b], c], d] *)
bbgodfrey
  • 61,439
  • 17
  • 89
  • 156
5

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]

m_goldberg
  • 107,779
  • 16
  • 103
  • 257