Last active
August 29, 2015 14:28
-
-
Save nuclearace/93eaec2fd4c3626f8fad 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
| abstract class AbsIterator { | |
| type T | |
| def hasNext: Boolean | |
| def next: T | |
| } | |
| trait RichIterator extends AbsIterator { | |
| def foreach(f: T => Unit) { while (hasNext) f(next) } | |
| } | |
| class StringIterator(s: String) extends AbsIterator { | |
| type T = Char | |
| private var i = 0 | |
| def hasNext = i < s.length() | |
| def next = { val ch = s charAt i; i += 1; ch } | |
| } | |
| object Main extends App { | |
| class Iter extends StringIterator("This in swift when?") with RichIterator | |
| val iter = new Iter | |
| iter foreach println | |
| } |
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
| protocol AbsIterator { | |
| typealias T | |
| var hasNext: Bool {get} | |
| func next() -> T | |
| } | |
| protocol RichItarator: AbsIterator { | |
| func forEach(f: T -> Void) | |
| } | |
| extension RichItarator { | |
| func forEach(f: T -> Void) { | |
| while hasNext { | |
| f(next()) | |
| } | |
| } | |
| } | |
| class StringIterator: AbsIterator { | |
| let string: String | |
| typealias T = Character | |
| var i = 0 | |
| var hasNext: Bool { | |
| return i < string.characters.count | |
| } | |
| func next() -> T { | |
| return string[string.startIndex.advancedBy(i)] | |
| } | |
| init(string: String) { | |
| self.string = string | |
| } | |
| } | |
| extension StringIterator: RichItarator {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment