Skip to content

Instantly share code, notes, and snippets.

struct Linear<A> {
let x: A
let c: A // c stands for 'constant', it's the constant factor to the linear function
}
extension Linear: CustomStringConvertible where A: CustomStringConvertible {
var description: String { return "f(x) = \(x)x + \(c)" }
}
extension Linear: Equatable where A: Equatable {}
let i = Complex(real: 0.0, imm: 1.0)
let one = Complex(real: 1.0, imm: 0.0)
let other = Complex(real: Double.pi, imm: sqrt(2.0))
i * i == (-1) ◊ one
Complex.multId * i == i
other.magnitude
17.3 ◊ other
struct Complex: Equatable {
let real: Double
let imm: Double
}
extension Complex: CustomStringConvertible {
var description: String { return "\(real) + \(imm)i" }
}
extension Complex: TwoDimensions {
let doubleVect = Vector(fst: 1.0, snd: 1.0)
doubleVect.magnitude
extension Double: Multiplicative {
static var multId: Double { return 1.0 }
}
extension Double: Additive {
static var addId: Double {
return 0.0
}
}
print(xy.magnitude)
// 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)
}
}
prefix operator √
/// A protocol for getting the square root of a value
protocol SquareRoot {
static prefix func √(_ square: Self) -> Self
}
let x = Vector(fst: 1, snd: 0)
let y = Vector(fst: 0, snd: 1)
let xy = x + y
xy
3 ◊ xy
xy.magSquare
extension Vector: TwoDimensions {
static func make2D(_ fst: A, _ snd: A) -> Vector<A> {
return Vector(fst: fst, snd: snd)
}
}