Created
February 19, 2021 15:00
-
-
Save kana-sama/f838e6c8d2f16a99b1f9bd4f27492e2f to your computer and use it in GitHub Desktop.
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
| /** | |
| * We declare a package-level function main which returns Unit and takes | |
| * an Array of strings as a parameter. Note that semicolons are optional. | |
| */ | |
| fun main() { | |
| val tree = Node( | |
| 1, | |
| listOf( | |
| Node( | |
| 2, listOf( | |
| Node(3), | |
| Node(4), | |
| Node(5) | |
| ) | |
| ), | |
| Node(6) | |
| ) | |
| ) | |
| val list = preorder({ x -> "name: " + x.toString() }, tree) | |
| println() | |
| println(list) | |
| } | |
| fun <A, B> preorder(transform: (A) -> B, node: Node<A>) : List<B>{ | |
| return listOf(transform(node.rootLabel)) + | |
| node.subForest.flatMap { preorder(transform, it) } | |
| } | |
| data class Node<T>( | |
| val rootLabel: T, | |
| val subForest: List<Node<T>> = emptyList() | |
| ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment