Scalaでマネする。

与えられた木から、子→親への対応を作るという問題なのだが、これが簡単そうで実はなかなか奥が深そうだ。
いくつか回答を眺める中で、その中で、与えられた木から、子→親への対応を作る - MEMO:はてな支店が良く出来ていたので、練習がてらScalaで真似してみる。

object Tree {
  def main(args : Array[String]) : Unit = {
    var tree = ('root,('RClavicle,('RUpperArm,('RLowerArm,('RHand,Nil)::Nil)::Nil)::Nil)
                ::('LClavicle, ('LUpperArm, ('LLowerArm, ('LHand,Nil)::Nil)::Nil)::Nil)
                ::('RHip, ('RUpperLeg, ('RLowerLeg, ('RFoot,Nil)::Nil)::Nil)::Nil)
                ::('LHip, ('LUpperLeg, ('LLowerLeg, ('LFoot,Nil)::Nil)::Nil)::Nil)
                ::Nil);
      println(f(tree));
  }

  def f(tree:(Symbol,List[_])) : List[(Symbol,Symbol)] = tree match {
  case (_,Nil) => Nil;
  case (p,(c:Symbol,cs:List[_])::ps) => List((c,p))++f((c,cs))++f((p,ps));
  }
}

結果

List(('RClavicle,'root), ('RUpperArm,'RClavicle), ('RLowerArm,'RUpperArm), ('RHand,'RLowerArm), ('LClavicle,'root), ('LUpperArm,'LClavicle), ('LLowerArm,'LUpperArm), ('LHand,'LLowerArm), ('RHip,'root), ('RUpperLeg,'RHip), ('RLowerLeg,'RUpperLeg), ('RFoot,'RLowerLeg), ('LHip,'root), ('LUpperLeg,'LHip), ('LLowerLeg,'LUpperLeg), ('LFoot,'LLowerLeg))

最初の木の定義がやぼったい事に、scalaだと普通どうかくのかな。おしえてエロイ人><