bsleboda
(Blazej SLEBODA)
December 29, 2019, 11:35am
1
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?
bsleboda
(Blazej SLEBODA)
December 29, 2019, 11:52am
4
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
bsleboda
(Blazej SLEBODA)
December 29, 2019, 12:09pm
6
Type casting the initialResult argument, solves the problem.
bsleboda
(Blazej SLEBODA)
December 29, 2019, 12:10pm
7
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
bsleboda
(Blazej SLEBODA)
December 29, 2019, 12:41pm
9
Anyway, It's strange that Double(0)
doesn't solve the error but as Double
does.