Swiftで行列の積

前回は幼稚な感動を記事にしたわけですが、今回も引き続きそんなノリです。

protocol VectorProtocol {
    typealias ComponentType
    init( _ component : ( index : UInt ) ->ComponentType )
    static func dot( lhs: Self , _ rhs: Self ) -> ComponentType
}

protocol MatrixProtocol {
    typealias ComponentType
    typealias RowType
    typealias ColType
    func row( index : UInt ) -> RowType
    func col( index : UInt ) -> ColType
    init( _ component : ( row : UInt, col : UInt ) -> ComponentType )
}

func * < T : MatrixProtocol, U : MatrixProtocol
    where T.RowType : VectorProtocol,
    T.RowType == U.ColType, T.ColType == U.RowType,
    T.ComponentType == T.RowType.ComponentType >
    ( lhs: T, rhs: U ) -> T
{
    return T() { T.RowType.dot( lhs.row( $0 ), rhs.col( $1 ) ) }
}

row majorだろうが、column majorだろうが、2x3と3x4だろうが、各種正方行列だろうが、要素の型がなんであろうが、これからはプロトコル準拠するだけで済むのかぁ。良い時代だなぁ、しかし。ちょーでかい行列は使わないのでわかりません。