Comment detail

フォルダパス一覧のツリー構造への変換 (Nested Flatten)

作成はちょっと変則的なinjectと破壊的作用の組み合わせでハッシュでツリーを。

表示は素直な再帰で。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
path_list = %w(
abc\\def
abc\\def\\gh
abc\\def\\ij
abc\\jk\\lm
de
)

def dump_tree(h, pad="")
  h.sort_by{|k,v| k}.each{|k,v|
    print(pad, "┗", k, "\n")
    dump_tree(v, pad+"  ")
  }
end

h = {}
path_list.each{|path|
  path.split(/\\/).inject(h){|k,v|
    k[v] ||= {}
  }
}

dump_tree(h)
これはすばらしい!

感動したので、Squeak Smalltalk に意訳させていただきました。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
| pathList tree dumpTree |
pathList := #('abc\def' 'abc\def\gh' 'abc\def\ij' 'abc\jk\lm' 'de').

tree := Dictionary new.
pathList do: [:path |
    (path subStrings: #($\)) inject: tree into: [:tr :dir |
        tr at: dir ifAbsentPut: [Dictionary new]]].

dumpTree := [:tr :lev |
    tr keys asSortedCollection do: [:key |
        Transcript crtab: lev; show: key.
        (tr at: key) ifNotEmptyDo: [:child |
            dumpTree copy fixTemps value: child value: lev + 1]]].

World findATranscript: nil.
dumpTree copy fixTemps value: tree value: 0

"=>
abc
    def
        gh
        ij
    jk
        lm
de
"

Index

Feed

Other

Link

Pathtraq

loading...