Created
December 4, 2015 14:53
-
-
Save externvoid/7b8ee7cc4ef00c169a54 to your computer and use it in GitHub Desktop.
SwiftによるListのサンプルコード@Swift2.1+Terminal.App
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
enum List<T> { | |
case Cons(T, () -> List<T>) | |
case Nil | |
} | |
// list構造はlist要素が連なったものである。list要素はenumで定義する。 | |
// list構造は、cons関数で作る。リスト構造もリスト要素である。 | |
// リスト要素は、ConsまたはNil。Cons(T,(Function))、タプルを要素にする。 | |
// Cons関数の様に見えるが、タプルを内包している。 | |
func cons<T>(value: T, _ list: List<T>) -> List<T> { | |
return List.Cons(value) { list } | |
} | |
//func lazyCons<T>(value: T, f: () -> List<T>) -> List<T> { | |
// return List.Cons(value, f) | |
//} | |
let list = cons(1, cons(2, cons(3, .Nil))) | |
// car means the contents of address, cdr, the contens of decrement | |
extension List { | |
var car: T? { | |
switch self { | |
case let .Cons(car, _): | |
return car | |
case .Nil: | |
return nil | |
} | |
} | |
var cdr: List<T> { | |
switch self { | |
case let .Cons(_, cdr): | |
return cdr() | |
case .Nil: | |
return .Nil | |
} | |
} | |
} | |
struct ListGenerator<T> : GeneratorType { | |
typealias Element = T | |
init(_ list: List<T>) { | |
_list = list | |
} | |
mutating func next() -> Element? { | |
let car = _list.car | |
_list = _list.cdr | |
return car | |
} | |
var _list: List<T> | |
} | |
extension List : SequenceType { | |
func generate() -> ListGenerator<T> { | |
return ListGenerator(self) | |
} | |
} | |
let alist = cons(1, cons(2, cons(3, .Nil))) | |
for n in alist { | |
print(n) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment