Created
August 8, 2014 16:34
-
-
Save griotspeak/9c0df48abc294ef6a857 to your computer and use it in GitHub Desktop.
Slightly altered rendition of http://tel.github.io/2014/07/27/calkin-wilf-in-swift/
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
struct Tree<A> { | |
let val: A | |
let left: @autoclosure () -> Tree<A> | |
let right: @autoclosure () -> Tree<A> | |
} | |
struct Stream<A> { | |
let val: A | |
let next: @autoclosure () -> Stream<A> | |
} | |
func calkin(n: Int, m: Int) -> Tree<(Int, Int)> { | |
return Tree( | |
val: (n, m), | |
left: calkin(n+m, m), | |
right: calkin(n, n+m) | |
) | |
} | |
func interleave<A>(sa: Stream<A>, sb: Stream<A>) -> Stream<A> { | |
return Stream( | |
val: sa.val, | |
next: Stream( | |
val: sb.val, | |
next: interleave(sa.next(), sb.next()) | |
) | |
) | |
} | |
func traverse<A>(t: Tree<A>) -> Stream<A> { | |
return Stream( | |
val: t.val, | |
next: interleave(traverse(t.left()), traverse(t.right())) | |
) | |
} | |
let rats: Stream<(Int, Int)> = traverse(calkin(1,1)) | |
func takeStream<A>(n: Int)(s: Stream<A>) -> [A] { | |
var res: [A] = [] | |
var s = s | |
for i in 0..<n { | |
res += [s.val] | |
s = s.next() | |
} | |
return res | |
} | |
println(takeStream(10)(s: rats)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment