Created
November 1, 2016 14:25
-
-
Save imaximix/ea816fcac11eff43ffa663fe4a86cd9d to your computer and use it in GitHub Desktop.
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
func cycle<A>(coll: [A]) -> AnyIterator<A> { | |
var cursor = 0 | |
let infiniteItems = AnyIterator { () -> A in | |
let itemToReturn = coll[cursor] | |
cursor += 1 | |
if (cursor > coll.count - 1) { | |
cursor = 0 | |
} | |
return itemToReturn | |
} | |
return infiniteItems | |
} | |
let ticTac = cycle(["tic", "tac"]) | |
print(ticTac.next()) // "tic" | |
print(ticTac.next()) // "tac" | |
print(ticTac.next()) // "tic" | |
print(ticTac.next()) // "tac" | |
print(ticTac.next()) // "tic" |
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
func take<A>(count: Int, coll: AnyIterator<A>) -> [A] { | |
var returnValue: [A] = [] | |
for _ in 1...count { | |
returnValue.append(coll.next()!) | |
} | |
return returnValue | |
} | |
let ticTac = cycle(["tic", "tac"]) | |
print(take(3, ticTac)) // ["tic", "tac" ,"tic"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment