def _msm_f(x, y, z, cost):
    """
    Helper function for MSM distance calculation
    """
    if (y <= x <= z) or (y >= x >= z):
        return cost
    else:
        return cost + min(abs(x - y), abs(x - z))