Skip to content

Instantly share code, notes, and snippets.

@griotspeak
Created August 8, 2014 16:34
Show Gist options
  • Save griotspeak/9c0df48abc294ef6a857 to your computer and use it in GitHub Desktop.
Save griotspeak/9c0df48abc294ef6a857 to your computer and use it in GitHub Desktop.
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