Created
July 19, 2015 22:40
-
-
Save oisdk/5ebb668fb4f1780a63c4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public protocol VectorType { | |
typealias Scalar | |
var endIndex: Int {get} | |
subscript(_: Int) -> Scalar {get set} | |
init() | |
} | |
public struct EmptyVector<T> : VectorType { | |
public init() {} | |
typealias Scalar = T | |
public let endIndex: Int = 0 | |
public subscript(idx: Int) -> Scalar { | |
get { fatalError("Index out of range") } | |
set { fatalError("Index out of range") } | |
} | |
} | |
public struct Vector<Tail : VectorType> : VectorType, CollectionType { | |
typealias Scalar = Tail.Scalar | |
private var (scalar, tail): (Scalar, Tail) | |
public var startIndex: Int { return 0 } | |
public var endIndex: Int { return tail.endIndex + 1 } | |
public subscript(idx: Int) -> Scalar { | |
get { return idx == 0 ? scalar : tail[idx - 1] } | |
set { idx == 0 ? (scalar = newValue) : (tail[idx - 1] = newValue) } | |
} | |
private init(head: Scalar, tail: Tail = Tail()) { | |
scalar = head | |
self.tail = tail | |
} | |
public init() { preconditionFailure() } | |
} | |
infix operator ⋮ { | |
associativity right | |
precedence 1 | |
} | |
public func ⋮ <T> (lhs: T, rhs: T) -> Vector<Vector<EmptyVector<T>>> { | |
return Vector(head: lhs, tail: Vector(head: rhs)) | |
} | |
public func ⋮ <T, U : VectorType where U.Scalar == T> (lhs: T, rhs: Vector<U>) -> Vector<Vector<U>> { | |
return Vector(head: lhs, tail: rhs) | |
} | |
let some = 1 ⋮ 2 ⋮ 3 ⋮ 4 // Vector<Vector<Vector<Vector<EmptyVector<Int>>>>> | |
Array(some) // [1, 2, 3, 4] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment