Forked from evacchi/Algebraic Data Types in Kotlin
Created
December 31, 2015 19:02
-
-
Save throughnothing/dc1b719b2f06bca68eb6 to your computer and use it in GitHub Desktop.
This file contains 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
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)) | |
)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment