Guest User

Untitled

a guest
Feb 18th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. defmodule Treewalk do
  2. @type tree :: {:node, integer(), tree(), tree()} | nil
  3.  
  4. def depth({:node, value, nil, nil}, _fun) do
  5. value
  6. end
  7.  
  8. def depth({:node, value, nil, right}, fun) do
  9. fun.(value, depth(right, fun), nil)
  10. end
  11.  
  12. def depth({:node, value, left, nil}, fun) do
  13. fun.(value, depth(left, fun), nil)
  14. end
  15.  
  16. def depth({:node, value, left, right}, fun) do
  17. fun.(value, depth(left, fun), depth(right, fun))
  18. end
  19.  
  20. # The function to be run on each
  21. # node of the tree which is passed
  22. # the current value, the result of
  23. # running the funciton on the left
  24. # branch and the result of running
  25. # the function on the right branch
  26. def adder(a, b, nil) do
  27. a + b
  28. end
  29.  
  30. def adder(a, b, c) do
  31. a + b + c
  32. end
  33.  
  34. # Test tess
  35. def tree do
  36. {:node,
  37. 1,
  38. {:node, 2,
  39. {:node, 4, nil, nil},
  40. nil
  41. },
  42. {:node, 3,
  43. nil,
  44. {:node, 4, nil, nil}
  45. }
  46. }
  47. end
  48.  
  49. # run a test, returns 14
  50. def test do
  51. depth(tree(), &adder/3)
  52. end
  53. end
Add Comment
Please, Sign In to add comment