Skip to content

Instantly share code, notes, and snippets.

extension Magnitude where
Self: TwoDimensions,
Self.ComponentVal: Multiplicative,
Self.ComponentVal: Additive,
Self.ComponentVal == Self.MagVal {
var magSquare: Self.MagVal {
return self.fst * self.fst + self.snd * self.snd
}
}
/// A protocol for getting the magnitude of an object
protocol Magnitude {
associatedtype MagVal: Comparable
var magSquare: MagVal { get }
}
extension Additive where Self: TwoDimensions, Self.ComponentVal: Additive {
static var addId: Self {
return Self.make2D(Self.ComponentVal.addId, Self.ComponentVal.addId)
}
static func + (lhs: Self, rhs: Self) -> Self {
return make2D(lhs.fst + rhs.fst, lhs.snd + rhs.snd)
}
}
infix operator ◊: MultiplicationPrecedence
/// Protocol for scalar multiplication operation
protocol Scalar {
associatedtype ScalarVal
static func ◊ (_ lhs: ScalarVal, _ rhs: Self) -> Self
}
struct Vector<A> {
let fst: A
let snd: A
}
extension Vector: CustomStringConvertible where A: CustomStringConvertible {
var description: String {
return "Vector<\(String(describing: A.self))>(\(fst.description), \(snd.description))"
}
}
extension Vector: TwoDimensions {
static func make2D(_ fst: A, _ snd: A) -> Vector<A> {
return Vector(fst: fst, snd: snd)
}
}
let x = Vector(fst: 1, snd: 0)
let y = Vector(fst: 0, snd: 1)
let xy = x + y
xy
3 ◊ xy
xy.magSquare
prefix operator √
/// A protocol for getting the square root of a value
protocol SquareRoot {
static prefix func √(_ square: Self) -> Self
}
// Magnitude has an extra field for types which have a square root function
extension Magnitude where Self.MagVal: SquareRoot {
var magnitude: Self.MagVal {
return √(self.magSquare)
}
}
print(xy.magnitude)