Skip to content

Instantly share code, notes, and snippets.

@adamkuipers
Created December 8, 2015 20:44
Show Gist options
  • Save adamkuipers/34b9f2a2d2dcc0b78dae to your computer and use it in GitHub Desktop.
Save adamkuipers/34b9f2a2d2dcc0b78dae to your computer and use it in GitHub Desktop.
Heterogeneous List in Swift
//: Playground - noun: a place where people can play
protocol HList {}
struct HNil: HList {}
struct HCons<Element, List: HList>: HList {
let head: Element
let tail: List
}
infix operator |*| { associativity right }
func |*| <E, L: HList>(element: E, rest: L) -> HCons<E, L> {
return HCons(head: element, tail: rest)
}
// Example
struct Key {
let value: Int
init(_ value: Int) {
self.value = value
}
}
struct Name {
let value: String
init(_ value: String) {
self.value = value
}
}
protocol Breed {}
struct Cow: Breed {}
struct Price {
let value: Double
init(_ value: Double) {
self.value = value
}
}
typealias Animal = HCons<Key, HCons<Name, HCons<Breed, HCons<Price, HNil>>>>
let angus: Animal = Key(42)
|*| Name("Angus")
|*| Cow()
|*| Price(75.5)
|*| HNil()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment