generalize distance function