Skip to content

Instantly share code, notes, and snippets.

@evacchi
Created September 5, 2014 18:20
Show Gist options
  • Save evacchi/d6a1c93730b9b843982c to your computer and use it in GitHub Desktop.
Save evacchi/d6a1c93730b9b843982c to your computer and use it in GitHub Desktop.
trait Tree
data object Empty : Tree
data class Leaf(val value: Int) : Tree
data class Node(val left: Tree, val right: Tree) : Tree
fun max(x:Int, y:Int):Int = if (x > y) x else y
fun depth(t: Tree): Int = when (t) {
is Empty -> 0
is Leaf -> 1
is Node -> 1 + max(depth(t.left), depth(t.right))
// unfortunately, the else branch is required
else -> throw NoWhenBranchMatchedException()
}
fun main(args: Array<String>) {
println(depth(
Node(Node(Leaf(1), Leaf(2)), Leaf(3))
))
}
@hastebrot
Copy link

Thanks for the sample code and the link to the issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment