Factor out the fold function from apply_mappings

This simplifies the code a bit.