[swift-users] Swift Initializer Generics

Tyler Fleming Cloutier cloutiertyler at aol.com
Mon Jan 18 20:34:19 CST 2016


Thanks for your responses!

Yes, it is true that I would like to use the Accelerate framework as much as possible. And since Surge is just a thin wrapper for that I wanted to reuse that functionality.

Dmitri, your suggestion is interesting regarding protocols, but I was giving it a try and I’m not sure exactly how you could accomplish it. For example, I tried the following.

protocol Summable: ArrayLiteralConvertible, CollectionType, _DestructorSafeContainer {
    typealias T: FloatingPointType, FloatLiteralConvertible
    func sum() -> T
}

extension Summable {
    func sum() -> T {
        var result: T = 0.0
        vDSP_sve(self, 1, &result, vDSP_Length(self.count)) // Cannot convert value of type 'Self' to expected argument type 'UnsafePointer<Float>'
        return result
    }
}

Well not only did that produce an error, but it doesn’t really makes sense or accomplish the goal because I haven’t distinguished between Float and Double. Neither does the following which has a vague error message.

protocol Summable: CollectionType {
    typealias Element: FloatingPointType, FloatLiteralConvertible
    func sum() -> Element
}

extension Array: Summable { // Type 'Array<Element>' does not conform to protocol 'Summable'
    func sum() -> Element {
        var result: Element = 0.0
        vDSP_sve(self, 1, &result, vDSP_Length(self.count))
        return result
    }
}

I suspect I’m misunderstanding your suggestion since I can’t quite work out how to do this. I’ve been wrangling the type checker here for a while, but I don’t know what the devil to do. With the different syntax for associated types, generic parameters, and constraints it’s a bit difficult to explore different without knowing exactly what to do.

Thanks,

Tyler


> On Jan 18, 2016, at 5:09 PM, Dmitri Gribenko <gribozavr at gmail.com> wrote:
> 
> On Mon, Jan 18, 2016 at 5:06 PM, David Turnbull via swift-users
> <swift-users at swift.org> wrote:
>> How about this...
>> 
>> public func dot<genType:FloatingPointVectorType>(x:genType, _ y:genType) ->
>> genType.Element {
>> 
>>    let a = genType(x, y, *)
>> 
>>    return a.reduce(genType.Element(0)) { $0 + ($1 as! genType.Element) }
>> 
>> }
> 
> This won't be calling into Accelerate.  The assumption is that
> Accelerate is manually-optimized and heavily tuned, and it will be
> faster than a naive Swift implementation.
> 
> Dmitri
> 
> -- 
> main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
> (j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160118/620db29a/attachment.html>


More information about the swift-users mailing list