We already have a function for this: fold.