This is listed as one of the “Hard” problem in 7 languages 7 weeks book. "Represent a tree of sentences as tuples. Traverse the tree, presenting an indented list.
I think I have solved it, but I’m wondering if there is a cleaner way to do this without all the conditionals. Thanks!
Book example:
{“See spot run.”, {“See spot sit”, “See spot run”}} will print
See spot run.
See spot sit
See spot run
And my example:
TreeRecurse.print_tree({"See spot.", {{"See spot sit.", {"Sitting down.", {"Run spot", {"Runnn!"}}}}, "See spot run."}}, "")
will produce the output:
See spot.
See spot sit.
Sitting down.
Run spot
Runnn!
See spot run.
defmodule TreeRecurse do
def print_tree({leaf}, indent), do: IO.puts "#{indent}#{leaf}"
def print_tree({root,{lone}},indent) do
IO.puts "#{indent}#{root}"
if is_tuple(lone) do
print_tree(lone, indent <> " ")
else
print_tree({lone}, indent <> " ")
end
end
def print_tree({root,{left,right}},indent) do
IO.puts "#{indent}#{root}"
if is_tuple(left) do
print_tree(left, indent <> " ")
else
print_tree({left}, indent <> " ")
end
if is_tuple(right) do
print_tree(right, indent <> " ")
else
print_tree({right}, indent <> " ")
end
end
end