manually define reduce function