【发布时间】:2015-02-03 19:20:05
【问题描述】:
首先,这里简要介绍一下dot product 是什么。
我希望能够拥有一段代码,我可以通过以下方式使用它:
let x = Vector<Double>(dimensions: 3)
let y = Vector<Double>(dimensions: 3)
//...
//assign some values (coordinates) to x and y
//x.dotProduct(y)
如何将dotProduct 实现为类 方法?
以下是不起作用的:
func dot(vector: Point<T>) -> Double {
var sum: Double = 0.0
for index in 0...vector.size {
sum += sum + vector[index] * point[index]
}
}
错误信息是:
error: cannot invoke '*' with an argument list of type '(@lvalue T, $T14)'
新func dot:
func dot(vector: Point<T>) -> T {
var sum = 0 as T
println(point.count)
for index in 0..<point.count{
println(vector[index])
println(point[index])
sum += vector[index] * point[index]
}
return sum
}
【问题讨论】:
-
定义“不起作用”。
-
正如我在回答您之前的问题stackoverflow.com/questions/28302650/… 时试图解释的那样,您必须定义一个具有所需操作“加法”和“乘法”的协议。这是关于定义通用点积的类似问题:stackoverflow.com/questions/25592838/…(代码基于此答案:stackoverflow.com/a/24047239/1187415)。
-
@MartinR 我根本无法让这些工作。
-
是从你之前的问题中指出的类吗? Vector又是如何定义的?
-
x.dotProduct(y) 是没有好处的坏事。 x •= y 是要走的路。 github.com/mattt/Euler/blob/master/Euler.swift
标签: swift operator-overloading