Skip to content

Instantly share code, notes, and snippets.

@evacchi
Created September 5, 2014 18:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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))
))
}
@orospakr
Copy link

FWIW, here's the relevant ticket in the Kotlin issue tracker: https://youtrack.jetbrains.com/issue/KT-1753

@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