7
$\begingroup$

Given a function f and a list {a,b,c,d,e} how can I compactly tell mathematica to return f[a,f[b,f[c,f[d,e]]]]?

It seems that Apply can do the job but I cannot make it work as I want.

$\endgroup$
  • 1
    $\begingroup$ What you want to do is best expressed by a Fold operation i.e. Fold[f,list]. Check out the documentation, it should be quite straightforward. If you need help you can ask again. $\endgroup$ – AndreasP Oct 24 '16 at 14:54
  • $\begingroup$ Ah, yes! I knew that there should be a way, I didn't know how it was called. Thanks! $\endgroup$ – tst Oct 24 '16 at 14:56
  • $\begingroup$ @AndreasP It's not that straightforward: Fold[f, Reverse@{a, b, c, d, e}] gives f[f[f[f[e, d], c], b], a], while the OP wants the arguments of every f to be in reversed order. $\endgroup$ – corey979 Oct 24 '16 at 15:03
  • 4
    $\begingroup$ Thanks for the correction @corey979, I didn't look at the question that closely, my bad. For completions sake, this'd work: Fold[f[#2, #1] &, Reverse@{a, b, c, d, e}] $\endgroup$ – AndreasP Oct 24 '16 at 15:18
  • 1
    $\begingroup$ A useful guide is Functional Iteration $\endgroup$ – Bob Hanlon Oct 24 '16 at 15:25
12
$\begingroup$

The function you want to use is Fold which does almost what you want to do i.e.

Fold[f,{a,b,c}]
Out[] := f[f[f[a, b], c], d]

Above operation is called FoldRight in other other languages, because it folds the function from left to the right over the list of arguments. Your question asks for a FoldLeft which you can easily implement by

  1. Reversing the inputlist
  2. Reversing the argument-order of f

The former can be achieved by a simple Reverse on the list, the latter by switching the arguments to the function f by defining an anonymous function f[#2,#1]&.

Thus you get your result with

Fold[f[#2, #1] &, Reverse@{a, b, c, d, e}]
Out[]:= f[a, f[b, f[c, f[d, e]]]]
$\endgroup$
  • $\begingroup$ An explicit definition for foldLeft: foldLeft[func_,x_,list_]:=Fold[func[#2, #1] &,x, Reverse@list] $\endgroup$ – Kvothe Oct 30 '18 at 14:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.