ruby - How to flatten a structure of embedded Set and Hash -
i convert embedding structure flat one.
- an embedding structure set of 0 or more objects, such as: string or hash having string key , other embedding structure value.
- a flat structure set of arrays or strings.
here examples:
t( set[] ) # => set[] t( set[ 'foo' ] ) # => set[ ['foo'] ] t( set[ 'foo0', 'foo1', 'foo2' ] ) # => set[ ['foo0'], ['foo1'], ['foo2'] ] t( set[ 'foo' => set[ 'bar' ] ] ) # => set[ ['foo', 'bar'] ] t( set[ 'foo' => set[ 'bar0', 'bar1', 'bar2' ] ] ) # => set[ ['foo', 'bar0'], # ['foo', 'bar1'], # ['foo', 'bar2'] ] t( set[ {'foo' => set[ 'bar0', 'bar1', 'bar2' ]}, {'foo' => set[ 'bar0', 'bar1', 'bar2' ]} ] ) # => set[ ['foo', 'bar0'], # ['foo', 'bar1'], # ['foo', 'bar2'], # ['foo', 'bar0'], # ['foo', 'bar1'], # ['foo', 'bar2'] ] t( set[ {'foo' => set[ {'foo' => set[ 'bar' ]} ]} ] ) # => set[ ['foo', 'foo', 'bar'] ] t( set[ {'foo' => set[ {'foo' => set[ 'bar' ]} ]}, 'baz' ] ) # => set[ ['foo', 'foo', 'bar'], # 'baz' ] t( set[ {'foo' => set[ {'foo' => set[ 'bar0', 'bar1' ]} ]}, 'baz' ] ) # => set[ ['foo', 'foo', 'bar0'], # ['foo', 'foo', 'bar1'], # ['baz'] ] t( set[ {'foo' => set[ {'foo' => set[ 'bar0', {'bar1' => set[ {'abc' => set[ 'def' ]} ]} ]} ]}, 'baz' ] ) # => set[ ['foo', 'foo', 'bar0'], # ['foo', 'foo', 'bar1', 'abc', 'def'], # ['baz'] ]
i think should use resistivity convert given structure. have no idea implementation. please feel free example of t
function.
edit:
in other words, develop embedding structure flatten structure.
we can see embedding structure such expression factors. , if multiply them, flatten structure returned.
recursion friend:
require 'set' def t_h(inp, prefix = []) if (inp.is_a?(hash)) result = [] inp.each |k,v| pprefix = prefix.dup result << t_h(v, pprefix << k) end return result.flatten(1) elsif (inp.is_a?(set)) result = [] inp.each |el| result << t_h(el, prefix) end return result.flatten(1) else pprefix = prefix.dup return [ pprefix << inp ] end end def t(inp) set.new(t_h(inp)) end # examples t(set[ 'foo' => set[ 'bar' ] ]) t(set[ 'foo' => set[ 'bar0', 'bar1', 'bar2' ] ]) t( set[ {'foo' => set[ 'bar0', 'bar1', 'bar2' ]}, {'foo' => set[ 'bar0', 'bar1', 'bar2' ]} ] )
code far optimal, idea.
Comments
Post a Comment