在Scala中转换玫瑰树

时间:2017-10-31 00:57:28

标签: scala breadth-first-search

This posting展示了如何遍历Scala中的玫瑰树。我想做类似的事情:在玫瑰树中的每个CNode上调用一个方法。以下是CNode定义:

case class CNode(
  name: String,
  helpMessage: String = "",
  children: List = Nil,
  alias: String = ""
)

以下是方法定义:

def node(objects: AnyRef*): SomeReturnValue

以下是一些测试数据:

val cNodes = List(
  CNode("account",
    helpMessage = "Account management", children =  List(
      CNode("import", children = List(CNode("<keyfile>"))),
      CNode("list",   helpMessage = "List accounts"),
      CNode("new",    helpMessage = "Create a new account"),
      CNode("update", children = List(CNode("<accountAddress>")))
    )
  ),
  CNode("javascript"),
  CNode("help")
)

所以,我想要完成的是将上面的List[CNode]转换为这样的递归调用结构:

val result = List(
  node("account", children = List(
    node("import", children = List(node("<keyfile>"))),
    node("list"),
    node("new"),
    node("update", children = List(node("<accountAddress>")))
  ),
  node("javascript"),
  node("help")
)

1 个答案:

答案 0 :(得分:0)

骑自行车回家我意识到有一种解决问题的简单方法:

implicit def cNodeToNode(cNode: CNode): Node = 
  node(cNode.name :: cNode.children.cNodes.map(cNodeToNode).toList: _*)