Thursday, December 22, 2016

Small experiment with dependent types in Swift 3

//: Playground - noun: a place where people can play

import Cocoa

// warmup exercise
// get the types of variables using swift reflection
let x = Mirror(reflecting: (1, 2, "e"))
let y = Mirror(reflecting: (3, 4, "hello"))
print(x.subjectType)
// compare types
print(x.subjectType == y.subjectType)

class TypeT<T> { }
// return value is a Mirror (Swift jargon for reflection of types)
// this value depends on the value of the first param
func value<T>(_ val: Int, blank: T) -> Mirror {
    if(val == 0) {
        // if val is zero, then return the type of blank
        return Mirror(reflecting: blank)
    }
    // otherwise, wrap the type of blank inside a TypeT and recurse.
    return value(val - 1, blank: TypeT<T>())
}

let x1 = value(3, blank: 0) // Mirror for TypeT<TypeT<TypeT<Int>>>

0 comments: