First implementation of fold function based on prefix matching