2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Kotlinの末尾再帰(tailrec)のサンプルコード

Posted at

Scalaの末尾再帰(tailrec)のサンプルコード - QiitaをKotlinに翻訳したもの。

interface Node
data class Directory(val name: String, val children: List<Node> = listOf()) : Node
data class File(val name: String) : Node

val fileTree =
        Directory("Users", listOf(
                Directory("alice", listOf(
                        File(".bashrc"),
                        Directory(".Trash"),
                        Directory("Desktop", listOf(
                                File("photo.jpg"),
                                File("document.docx"),
                                File("spreadsheet.xlsx")
                        ))
                ))
        ))

tailrec fun flattenFilesytem(tree: List<Node>, filenames: List<String> = listOf()): List<String> {
    val first = tree.firstOrNull()
    val rest = tree.drop(1)
    return when (first) {
        is File -> flattenFilesytem(rest, filenames.plus(first.name))
        is Directory -> flattenFilesytem(rest + first.children, filenames.plus(first.name))
        else -> filenames
    }
}

flattenFilesytem(listOf<Node>(fileTree))
//=> res27: kotlin.collections.List<kotlin.String> = [Users, alice, .bashrc, .Trash, Desktop, photo.jpg, document.docx, spreadsheet.xlsx]
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?