How to write a generic function for floating point values in swift

人走茶凉 提交于 2020-01-02 08:01:59

问题


I would like to call floating point methods on floating point types in swift.

func example<T : FloatingPoint>(_ x:T) -> T {
    return cos(cbrt(x + 1))
}

Is there a better way to do so than this?

protocol SupportsFloatingPoint : FloatingPoint {
    var cubeRoot:Self { get }
    var cosine:Self { get }
}

extension Double : SupportsFloatingPoint {
    var cubeRoot:Double { return Darwin.cbrt(self) }
    var cosine:Double { return Darwin.cos(self) }
}

extension Float : SupportsFloatingPoint {
    var cubeRoot:Float { return Darwin.cbrt(self) }
    var cosine:Float { return Darwin.cos(self) }
}

func cbrt<T : SupportsFloatingPoint>(_ x:T) -> T {
    return x.cubeRoot
}

func cos<T : SupportsFloatingPoint>(_ x:T) -> T {
    return x.cosine
}

func example<T : SupportsFloatingPoint>(_ x:T) -> T {
    return cos(cbrt(x - 1))
}

Note that the addition operator is lost here. You can do -, * and / but not + on SupportsFloatingPoint types.


回答1:


You don't need a new protocol. You can extend the existing FloatingPoint protocol for supported types:

// Just for fun :)
prefix operator √
prefix operator ∛

extension FloatingPoint where Self == Double {
    var squareRoot: Self { return sqrt(self) }
    var cubeRoot: Self { return cbrt(self) }
    var sine: Self { return sin(self) }
    var cosine: Self { return cos(self) }

    static prefix func √(_ x: Self) -> Self { return x.squareRoot }
    static prefix func ∛(_ x: Self) -> Self { return x.cubeRoot }
}

extension FloatingPoint where Self == Float {
    var squareRoot: Self { return sqrt(self) }
    var cubeRoot: Self { return cbrt(self) }
    var sine: Self { return sin(self) }
    var cosine: Self { return cos(self) }

    static prefix func √(_ x: Self) -> Self { return x.squareRoot }
    static prefix func ∛(_ x: Self) -> Self { return x.cubeRoot }
}

print(Double.pi.cosine)
print(√25.0)
print(∛8.0)

Admittedly, there's a lot of code duplication, which I'm currently investigating how to minimize. On the bright side, at least this is all static, inlineable code that'll produce very fast machine code.



来源:https://stackoverflow.com/questions/43175915/how-to-write-a-generic-function-for-floating-point-values-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!