Skip to content

Instantly share code, notes, and snippets.

@DevAndArtist
Last active March 1, 2017 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DevAndArtist/b0c92c6443f325bfce33bff1e7a9c4bc to your computer and use it in GitHub Desktop.
Save DevAndArtist/b0c92c6443f325bfce33bff1e7a9c4bc to your computer and use it in GitHub Desktop.

Vectors

  • A vector contains at least one type.
  • vector T - is a list of type T of an arbitrary length, such as T1, T2, ...
  • vector(n) T - is a list with the length of maximal n T's, such as T1, T2, ... , Tn
// vectorized tuple with arbitrary length (like an existetial that can accept a tuple of type `T` of any length)
var t1: (vector Int) = (1, 2)
t1 = (1, 2, 3)
t1 = (1, 2, 3, 4)

// vectorized tuple of fixed length
let t2: (vector(10) Int) = (1, 2, 3, 4, 5, 6, 7, 8, 9, 0)

// replacing the variadic syntax `T...` with vectors
func foo1(_: vector Int)
func foo2(_: (vector Int))
func foo3(_: vector (vector Int))

foo1(1, 2, 3, 4)
foo2((1, 2, 3, 4, 5))
foo3((1, 2), (1, 2, 3, 4), (1, 2, 3))

// variadic with fixed length
func foo4(_: vector(3) Int)
func foo5(_: vector(3) (vector(3) Int))

foo4(1, 2, 3)
foo5((1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4))

// `foo5` would be equivalent to `func foo5(_: (Int, Int, Int), _: (Int, Int, Int), _: (Int, Int, Int))`
func foo3(_: vector (vector Int))

Variadic generics

  • generic T - a constraint applied to T to indicated that T is not fixed and can be changed iteratively.
  • generic does not provide any information about the length of the parameter list.
// combined with vectors we'll get variadic generics

// the reason why we need both `vector` and `params` is to be able to tell the compiler that `T` has
// an arbitrary paramater length (vector) *and* that `T` can change iteratively (generic)
struct ZipSequence<vector generic T> : Sequence where T : Sequence { ... }

func zip<vector generic T>(_ sequences: vector T) -> ZipSequence<vector T> where T : Sequence { ... }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment