Implementation of fold.