Skip to content

Instantly share code, notes, and snippets.

@kana-sama
Created February 19, 2021 15:00
Show Gist options
  • Select an option

  • Save kana-sama/f838e6c8d2f16a99b1f9bd4f27492e2f to your computer and use it in GitHub Desktop.

Select an option

Save kana-sama/f838e6c8d2f16a99b1f9bd4f27492e2f to your computer and use it in GitHub Desktop.
/**
* 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