-
-
Save Codelaby/77813e4f8b1deafdd93838701439355a to your computer and use it in GitHub Desktop.
Recursion with Swift Coroutines
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
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