这里有人可以看看代码并告诉我它有什么问题吗?我基本上尝试构建一些对某些原始类型(如Int
,Float
,Double
等)进行操作的泛型函数。
不幸的是,我无法正常工作。这是(部分)工作的代码:
// http://stackoverflow.com/a/24047239/2282430
protocol SummableMultipliable: Equatable {
func +(lhs: Self, rhs: Self) -> Self
func *(lhs: Self, rhs: Self) -> Self
}
extension Double: SummableMultipliable {}
func vec_dot<T where T: SummableMultipliable>(a : [T], b: [T]) -> Double {
assert(a.count == b.count, "vectors must be of same length")
var s : Double = 0.0
for var i = 0; i < a.count; ++i {
let x = (a[i] * b[i]) as Double
s = s + x
}
return s
}
现在我写的时候:
var doubleVec : [Double] = [1,2,3,4]
vec_dot(doubleVec, doubleVec)
返回30
的正确结果。好的,到目前为止一切顺利。当我尝试传递Int
s:
extension Int : SummableMultipliable {}
var intVec : [Int] = [1,2,3,4]
vec_dot(intVec, intVec)
的Bam!抛出异常:
let x = (a[1] * b[1]) as Double
* thread #1: tid = 0x139dd0, 0x00000001018527ad libswiftCore.dylib`swift_dynamicCast + 1229, queue = 'com.apple.main-thread', stop reason = EXC_BREAKPOINT (code=EXC_I386_BPT, subcode=0x0)
* frame #0: 0x00000001018527ad libswiftCore.dylib`swift_dynamicCast + 1229
frame #1: 0x000000010d6c3a09 $__lldb_expr248`__lldb_expr_248.vec_dot <A : __lldb_expr_248.SummableMultipliable>(a=Swift.Array<T> at 0x00007fff5e5a9648, b=Swift.Array<T> at 0x00007fff5e5a9640) -> Swift.Double + 921 at playground248.swift:54
frame #2: 0x000000010d6c15b0 $__lldb_expr248`top_level_code + 1456 at playground248.swift:64
frame #3: 0x000000010d6c4561 $__lldb_expr248`main + 49 at <EXPR>:0
frame #4: 0x000000010165b390 FirstTestPlayground`get_field_types__XCPAppDelegate + 160
frame #5: 0x000000010165bea1 FirstTestPlayground`reabstraction thunk helper from @callee_owned () -> (@unowned ()) to @callee_owned (@in ()) -> (@out ()) + 17
frame #6: 0x000000010165ab61 FirstTestPlayground`partial apply forwarder for reabstraction thunk helper from @callee_owned () -> (@unowned ()) to @callee_owned (@in ()) -> (@out ()) + 81
frame #7: 0x000000010165bed0 FirstTestPlayground`reabstraction thunk helper from @callee_owned (@in ()) -> (@out ()) to @callee_owned () -> (@unowned ()) + 32
frame #8: 0x000000010165bf07 FirstTestPlayground`reabstraction thunk helper from @callee_owned () -> (@unowned ()) to @callee_unowned @objc_block () -> (@unowned ()) + 39
frame #9: 0x0000000101fedaac CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12
frame #10: 0x0000000101fe37f5 CoreFoundation`__CFRunLoopDoBlocks + 341
frame #11: 0x0000000101fe2fb3 CoreFoundation`__CFRunLoopRun + 851
frame #12: 0x0000000101fe29f6 CoreFoundation`CFRunLoopRunSpecific + 470
frame #13: 0x000000010208f2b1 CoreFoundation`CFRunLoopRun + 97
frame #14: 0x0000000101658be8 FirstTestPlayground`top_level_code + 3784
frame #15: 0x000000010165b3ba FirstTestPlayground`main + 42
frame #16: 0x0000000103cd9145 libdyld.dylib`start + 1
我尝试执行不同的演员:
let x = Double(a[i] * b[1])
错误:无法找到&#39; init&#39;接受提供的参数。
let y = a[i] * b[1]
let x = Double(y)
错误:无法调用&#39; init&#39;参数类型为&#39; T&#39;。
接下来,我试过了:
let y = Double(a[i]) * Double(b[1])
let x = y
错误:无法调用&#39; *&#39;使用类型&#39;(Double,Double&#39;)的参数列表。
我尝试了许多更多的东西。一旦我尝试将Int
作为通用类型传递,就不再有效了。
也许我只是缺少一些基本的东西,或者我太愚蠢了解通用编程。在C ++中,我将在2秒内完成。
答案 0 :(得分:5)
使用Int
数组调用时,a[i] * b[i]
为Int
,无法投射
与Double
一起as
。
要解决该问题,您可以更改vec_dot
功能以返回T
对象而不是Double
。
要使初始化var s : T = 0
有效,您必须SummableMultipliable
派生自IntegerLiteralConvertible
(Int
和Double
已符合):
protocol SummableMultipliable: Equatable, IntegerLiteralConvertible {
func +(lhs: Self, rhs: Self) -> Self
func *(lhs: Self, rhs: Self) -> Self
}
func vec_dot<T where T: SummableMultipliable>(a : [T], b: [T]) -> T {
assert(a.count == b.count, "vectors must be of same length")
var s : T = 0
for var i = 0; i < a.count; ++i {
let x = (a[i] * b[i])
s = s + x
}
return s
}
示例:
var doubleVec : [Double] = [1,2,3,4]
let x = vec_dot(doubleVec, doubleVec)
println(x) // 30.0 (Double)
var intVec : [Int] = [1,2,3,4]
let y = vec_dot(intVec, intVec)
println(y) // 30 (Int)
或者,如果矢量产品应始终生成Double
,则可以
在doubleValue()
协议中添加SummableMultipliable
方法:
protocol SummableMultipliable: Equatable {
func +(lhs: Self, rhs: Self) -> Self
func *(lhs: Self, rhs: Self) -> Self
func doubleValue() -> Double
}
extension Double: SummableMultipliable {
func doubleValue() -> Double { return self }
}
extension Int : SummableMultipliable {
func doubleValue() -> Double { return Double(self) }
}
func vec_dot<T where T: SummableMultipliable>(a : [T], b: [T]) -> Double {
assert(a.count == b.count, "vectors must be of same length")
var s : Double = 0
for var i = 0; i < a.count; ++i {
let x = (a[i] * b[i]).doubleValue()
s = s + x
}
return s
}
备注:正如@akashivskyy正确地说的那样,循环应该更快地写成
for i in 0 ..< a.count { ... }
如果你想获得幻想,给同事留下深刻印象或困惑,那么你可以 用一个表达式替换整个循环:
let s : T = reduce(Zip2(a, b), 0) { $0 + $1.0 * $1.1 }
答案 1 :(得分:3)
正如您可能已经注意到的那样,例外的原因是向下倾斜。公平地说,你要做的事情是非法的,编译器不应该允许你在第一时间这样做。
由于vec_dot
只知道T
是SummableMultipliable
,因此无法将其转换为Double
(就像它应该如何知道它一样)不是String
?)。
摆脱这个问题的简单方法是,摆脱通用约束并使用函数重载代替:
func vec_dot(a: [Double], b: [Double]) -> Double {
assert(a.count == b.count, "vectors must be of same length")
var s: Double = 0.0
for i in 0 ..< a.count {
let x = (a[i] * b[i])
s += x
}
return s
}
func vec_dot(a: [Int], b: [Int]) -> Double {
return vec_dot(a.map({ Double($0) }), b.map({ Double($0) }))
}
var doubleVec: [Double] = [1, 2, 3, 4]
vec_dot(doubleVec, doubleVec) // 30.0
var intVec: [Int] = [1, 2, 3, 4]
vec_dot(intVec, intVec) // 30.0
如果您仍想坚持使用协议和泛型,请参阅Martin R's answer。