Factor out distance function.