Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'prettyprint'
- # This form of the FP style creates a definition for fold()
- # for trees of the form [<value>, [<children>]]
- module FoldableTree
- # define fold for trees of the form [<value>, [<children>]]
- # recursively applies the FoldableTree type to each node
- def fold accumulator, &f
- # note the use of structural decomposition,
- # as (value, children) for elements in the tree
- inject(accumulator) do |accumulator, (value, children)|
- a2 = f.call accumulator, value
- children.extend FoldableTree
- children.fold a2, &f
- end
- end
- end
- root = [["root", [
- ["child", [
- ["grandkid", []],
- ["grandkid2", []]]],
- ["child2", []]]]]
- # Declare our tree to be an instance of FoldableTree
- root.extend FoldableTree
- # Fold across our foldable tree, collecting names in reverse
- p root.fold([]) do |a, name|
- # create a new array each time, rather than mutate a
- [a, name.reverse].flatten
- end
Add Comment
Please, Sign In to add comment