Reduce and The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions

I get an error when applying the reduce(0,+) part:

The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions

func euclideanDistanceBetween(_ point1: [Double], and point2: [Double]) -> Double {
    let productToBeSqrt = (0..<point1.count).map { point2[$0] - point1[$0] }.map { $0 * $0 }.reduce(0, +)
    let distance = sqrt(productToBeSqrt)
    return round(distance * 100) / 100
}

What can I do to help the compiler?

Try Double(0) or 0.0.

It doesn't help. The error is the same.

Okay then try this.


let productToBeSqrt: Double = zip(point1, point2)
  .map { ($1 - $0) * ($1 - $0) }
  .reduce(0 as Double, +)

You could also reduce some friction of unwanted iterations like so:


let productToBeSqrt = zip(point1, point2).reduce(0 as Double) { result, element in
  result + ((element.1 - element.0) * (element.1 - element.0))
}
1 Like

Type casting the initialResult argument, solves the problem.

that's my final solution:

func euclideanDistanceBetween(_ point1: [Double], and point2: [Double]) -> Double {
   return { round($0 * 100) / 100 } ( sqrt(zip(point2, point1).map(-).map { pow($0, 2.0) }.reduce(0 as Double, +)) as Double )
}

Keep in mind that this solution will iterate 4 x N where N is min(point1.count, point2.count) or simply zip(...).count. A single reduce function without all the redundant map calls will help reducing the friction.

And one more thing. zip avoids a possible crash from your original example. If point1.count > point2.count your original example would have trapped during point2[$0] call.

1 Like

Anyway, It's strange that Double(0) doesn't solve the error but as Double does.