与えられた木から、子→親への対応を作る - MEMO:はてな支店 を見て、再帰のみで表現されているところが、私の蚊程度の LISP 脳にもとても美しく映ったので、もちろんマクロ(というかテンプレート)のない Smalltalk に写しようもないのですが、雰囲気…というか動きだけ意訳で。
| tree translate | tree := #(Root (Spine (Neck (Head)) (RClavicle (RUpperArm (RLowerArm (RHand)))) (LClavicle (LUpperArm (LLowerArm (LHand))))) (RHip (RUpperLeg (RLowerLeg (RFoot)))) (LHip (LUpperLeg (LLowerLeg (LFoot))))). translate := [:tre | tre allButFirst ifEmpty: [#()] ifNotEmptyDo: [:children | {children first first -> tre first}, (translate copy fixTemps value: children first), (translate copy fixTemps value: {tre first}, children allButFirst)]]. ^translate copy fixTemps value: tree
これの直訳気味で Ruby でも。
class Array; def all_but_first; self[1..-1] end end tree = [:Root, [:Spine, [:Neck, [:Head]], [:RClavicle, [:RUpperArm, [:RLowerArm, [:RHand]]]], [:LClavicle, [:LUpperArm, [:LLowerArm, [:LHand]]]]], [:RHip, [:RUpperLeg, [:RLowerLeg, [:RFoot]]]], [:LHip, [:LUpperLeg, [:LLowerLeg, [:LFoot]]]]] def trans(parent, *children) children.empty? ? [] : [[children.first.first, parent]] + trans(*children.first) + trans(parent, *children.all_but_first) end trans(*tree)