implementation for both inject and reduce