Created
July 1, 2015 21:34
-
-
Save qwzybug/d36141559a4a61416547 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 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