Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- defmodule Treewalk do
- @type tree :: {:node, integer(), tree(), tree()} | nil
- def depth({:node, value, nil, nil}, _fun) do
- value
- end
- def depth({:node, value, nil, right}, fun) do
- fun.(value, depth(right, fun), nil)
- end
- def depth({:node, value, left, nil}, fun) do
- fun.(value, depth(left, fun), nil)
- end
- def depth({:node, value, left, right}, fun) do
- fun.(value, depth(left, fun), depth(right, fun))
- end
- # The function to be run on each
- # node of the tree which is passed
- # the current value, the result of
- # running the funciton on the left
- # branch and the result of running
- # the function on the right branch
- def adder(a, b, nil) do
- a + b
- end
- def adder(a, b, c) do
- a + b + c
- end
- # Test tess
- def tree do
- {:node,
- 1,
- {:node, 2,
- {:node, 4, nil, nil},
- nil
- },
- {:node, 3,
- nil,
- {:node, 4, nil, nil}
- }
- }
- end
- # run a test, returns 14
- def test do
- depth(tree(), &adder/3)
- end
- end
Add Comment
Please, Sign In to add comment