Vector.swift

precedencegroup DotProductPrecedence {
    lowerThan: AdditionPrecedence
    associativity: left
}

infix operator ∙ : DotProductPrecedence

class Vector<Element: Numeric> {
    var components = [Element]()

    // Variables conforming VectorProtocol
    var dimension: Int { return components.count }

    init(with array: [Element]) {
        components = array
    }
}

// Methods conforming Equatable
extension Vector: Equatable {
    static func == (lhs: Vector, rhs: Vector) -> Bool {
        guard lhs.dimension == rhs.dimension else {
            return false
        }

        for k in 0..<lhs.dimension {
            if lhs.components[k] != rhs.components[k] {
                return false
            }
        }

        return true
    }
}

// Methods
extension Vector {
    static func ∙ (lhs: Vector, rhs: Vector) -> Element {
        var temp = [Element]()
        for k in 0..<lhs.dimension {
            temp.append(lhs.components[k] * rhs.components[k])
        }
        return temp.reduce(0, {x, y in x + y})
    }
}

// Methods conforming CustomStringConvertible
extension Vector: CustomStringConvertible {
    var description: String {
        var string = "("
        for k in 0..<self.dimension {
            string += String(describing: self.components[k]) + ","
        }
        string.removeLast()
        return string + ")"
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s