Skip to content

Instantly share code, notes, and snippets.

@adellibovi
Last active March 22, 2025 18:05
Show Gist options
  • Save adellibovi/d220d487d14a8d118c361e8881006d8e to your computer and use it in GitHub Desktop.
Save adellibovi/d220d487d14a8d118c361e8881006d8e to your computer and use it in GitHub Desktop.
Recursion with Swift Coroutines
import Foundation
class Tree {
let left, right: Tree?
init(left: Tree?, right: Tree?) {
self.left = left
self.right = right
}
}
let tree = (1..<100000000).reduce(Tree(left: nil, right: nil), { prev, result in
Tree(left: prev, right: nil)
})
struct AsyncResursiveFunction<Input, Output> {
let closure: (Input, Self) async -> Output
func callAsFunction(_ input: Input) async -> Output {
await closure(input, self)
}
}
let asyncDepth = AsyncResursiveFunction<Tree?, Int> { tree, callRecursive in
guard let tree = tree else { return 0 }
return await 1 + max(callRecursive(tree.left), callRecursive(tree.right))
}
func depth(_ tree: Tree?) -> Int {
guard let tree = tree else { return 0 }
return 1 + max(depth(tree.left), depth(tree.right))
}
@main struct Main {
static func main() async {
await print(asyncDepth(tree))
// depth(tree) recursive stack overflow
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment