Calculates the contraction of a tensor.