Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I find it tedious to write out the following:

a = {1, 2, 3, 4};

Fold[f, First @ a, Rest @ a]
f[f[f[1, 2], 3], 4]

It becomes additionally cumbersome when working with held expressions, e.g.:

b = Hold[1 + 1, 2 + 2, 3 + 3, 4 + 4];

SetAttributes[g, HoldAll];

b /. _[x_, __] :> Fold[g, Unevaluated[x], Rest@b]
g[g[g[1 + 1, 2 + 2], 3 + 3], 4 + 4]

Likewise for FoldList. Is there a shorter syntax to achieve this?

share|improve this question

1 Answer 1

up vote 16 down vote accepted

Good News Everyone!

Two-parameter syntax for Fold and FoldList has been (silently) implemented!

Taliesin Beynon informs me that this was implemented in 2011, so check your older versions as well.

Using version 10:

Fold[f, a]

FoldList[f, a]
f[f[f[1, 2], 3], 4]

{1, f[1, 2], f[f[1, 2], 3], f[f[f[1, 2], 3], 4]}

And the held expression example:

Fold[g, b]
g[g[g[1 + 1, 2 + 2], 3 + 3], 4 + 4]

For full integration we merely need to update SyntaxInformation to match the implementation:

Unprotect[Fold, FoldList]

SyntaxInformation[Fold]     = {"ArgumentsPattern" -> {_, _, _.}};
SyntaxInformation[FoldList] = {"ArgumentsPattern" -> {_, _., {__}}};

Protect[Fold, FoldList]

(We could also update usage Messages but as this is, for the time being, undocumented I prefer not.)

For older versions you may (further) add the functionality with:

Unprotect[Fold, FoldList]

Fold[f_, h_[a_, b__]]     := Fold[f, Unevaluated @ a, h @ b]
FoldList[f_, h_[a_, b__]] := FoldList[f, Unevaluated @ a, h @ b]

Protect[Fold, FoldList]

Special thanks to those who made this happen!

share|improve this answer
    
Interesting! Thanks a lot for sharing! –  Yi Wang Jul 14 at 7:41
6  
@Mr.Wizard, I thought we had a discussion about it a while back - perhaps I forgot to mention that I could sneak it in;-) I am glad you like it. –  user21 Jul 14 at 8:33
    
It already works in M9 (Feb 7 2013 build). –  Yi Wang Jul 14 at 8:36
    
@user21 I'm terribly sorry if I forgot or somehow confounded you with someone else. (I have a very poor memory as I keep telling people.) Many thanks for getting this done! –  Mr.Wizard Jul 14 at 8:48
2  
@YiWang, I think, IIRC, it works from V9 onward. –  user21 Jul 14 at 8:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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