Завдання PrintMessages з книги Hand-On Scala Programming. Залучає просту рекурсію.
Li Haoyi написав:Write a recursive method printMessages that can receive an array of Msg class instances,
each with an optional parent ID, and use it to print out a threaded fashion. That means that child
messages are print out indented underneath their parents, and the nesting can be arbitrarily deep.
Вводимо таке:
printMessages(Array(
new Msg(0, None, "Hello"),
new Msg(1, Some(0), "World"),
new Msg(2, None, "I am Cow"),
new Msg(3, Some(2), "Hear me moo"),
new Msg(4, Some(2), "Here I stand"),
new Msg(5, Some(2), "I am Cow"),
new Msg(6, Some(5), "Here me moo, moo")
))
На виході має бути таке:
#0 Hello
#1 World
#2 I am Cow
#3 Hear me moo
#4 Here I stand
#5 I am Cow
#6 Here me moo, moo
▼моє рішення
object PrintMessages {
class Msg(val id: Int, val parent: Option[Int], val txt: String)
final val TAB = " "
def printMessages(messages: Array[Msg]): Unit = {
for (message <- messages) println(
s"${TAB * getIndentation(message.parent)}#${message.id} ${message.txt}"
)
def getIndentation(currentParent: Option[Int], tabCount: Int = 0): Int = {
if (currentParent.isEmpty) tabCount
else getIndentation(messages(currentParent.get).parent, tabCount + 1)
}
}
def main(args: Array[String]): Unit = {
printMessages(Array(
new Msg(0, None, "Hello"),
new Msg(1, Some(0), "World"),
new Msg(2, None, "I am Cow"),
new Msg(3, Some(2), "Hear me moo"),
new Msg(4, Some(2), "Here I stand"),
new Msg(5, Some(2), "I am Cow"),
new Msg(6, Some(5), "Here me moo, moo")
))
}
}