Implement `reduce` function