generic reduce with improved algorithm