Skip to content

Instantly share code, notes, and snippets.

@qwzybug
Created July 1, 2015 21:34
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 qwzybug/d36141559a4a61416547 to your computer and use it in GitHub Desktop.
Save qwzybug/d36141559a4a61416547 to your computer and use it in GitHub Desktop.
// Cons lists are kind of like linked lists
enum List<T> {
case Empty
indirect case Cons(T, List<T>) // doesn't compile yet. will soon.
mutating func add(item: T) {
switch self {
case .Empty:
self = .Cons(item, .Empty)
case .Cons(let value, var list):
list.add(item)
self = .Cons(value, list)
}
}
}
var list = List<String.Empty
list.add("Foo")
list.add("Bar")
// enumeration
extension List: SequenceType {
func generate() -> AnyGenerator<T> {
var list: List<T> = self
return anyGenerator({
switch list {
case .Empty:
return nil
case let .Cons(value, next):
list = next
return value
}
})
}
}
// sequences are handy
extension List: CustomStringConvertible {
var description: String {
return ",".join(self.map{ "\($0)" })
}
}
// immutable variant
extension List {
func cons(value: T) -> List<T> {
switch self {
case .Empty:
return .Cons(value, .Empty)
case let .Cons(val, list):
return .Cons(val, list.cons(value))
}
}
}
List<String>.Empty.cons("Foo").cons("Bar").description
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment