Created
December 8, 2015 20:44
-
-
Save adamkuipers/34b9f2a2d2dcc0b78dae to your computer and use it in GitHub Desktop.
Heterogeneous List in Swift
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
//: 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