Guest User

Untitled

a guest
Jan 21st, 2018
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. require 'prettyprint'
  2.  
  3. # This form of the FP style creates a definition for fold()
  4. # for trees of the form [<value>, [<children>]]
  5. module FoldableTree
  6.  
  7. # define fold for trees of the form [<value>, [<children>]]
  8. # recursively applies the FoldableTree type to each node
  9. def fold accumulator, &f
  10. # note the use of structural decomposition,
  11. # as (value, children) for elements in the tree
  12. inject(accumulator) do |accumulator, (value, children)|
  13. a2 = f.call accumulator, value
  14. children.extend FoldableTree
  15. children.fold a2, &f
  16. end
  17. end
  18. end
  19.  
  20. root = [["root", [
  21. ["child", [
  22. ["grandkid", []],
  23. ["grandkid2", []]]],
  24. ["child2", []]]]]
  25.  
  26. # Declare our tree to be an instance of FoldableTree
  27. root.extend FoldableTree
  28.  
  29. # Fold across our foldable tree, collecting names in reverse
  30. p root.fold([]) do |a, name|
  31. # create a new array each time, rather than mutate a
  32. [a, name.reverse].flatten
  33. end
Add Comment
Please, Sign In to add comment