具有二进制运算的泛型函数 [英] Generic function with binary operations
问题描述
我具有以下函数来返回数组的规范化版本,该数组的元素可以是Int,Double,Float.
I have the following function to return the normalized version of an array whose elements could be Int, Double, Float.
我收到下面第5行指示的错误.我以为数字协议可以解决二进制操作,但我猜不是.我在做什么错了?
I'm getting the error indicated on line 5 below. I thought the Numeric protocol would address the binary operation but I guess not. What am I doing wrong?
func normalizeArray<T: Comparable & Numeric>(a: [T]) -> [T] {
let min: T = a.min()!
let max: T = a.max()!
let n = a.map({ ($0 - min) / (max - min) }) <--- Binary operator '/' cannot be applied to two 'T' operands
return n
}
谢谢
推荐答案
Numeric
协议需要加,减和乘运算符,
但不是除法运算符.
The Numeric
protocol requires addition, subtraction and multiplication operators,
but not a division operator.
我不知道需要整数和浮点类型都符合的除法运算符的协议,因此您必须 实现两个重载函数:
I am not aware of a protocol which requires a division operator to which both integer and floating point types conform, therefore you have to implement two overloaded functions:
func normalizeArray<T: FloatingPoint>(a: [T]) -> [T] { ... }
func normalizeArray<T: BinaryInteger>(a: [T]) -> [T] { ... }
请注意,如果使用空白调用,您的实现将崩溃 阵列,我会建议
Note that your implementation will crash if called with an empty array, I'll suggest
func normalizeArray<T: BinaryInteger>(a: [T]) -> [T] {
guard let min = a.min(), let max = a.max() else {
return []
}
return a.map({ ($0 - min) / (max - min) })
}
这篇关于具有二进制运算的泛型函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!