Generalise to allow a comparator function to be supplied