Stylistic question: How to break out of a recursive tree processing?

I am currently building a small library that has to traverse a tree of nodes and transform this tree into a document. This tree traversal and transformation is done in a recursive function. Now, it might happen, that the tree contains unsupported nodes. And I want to provide an option for the function, that either skips these unsupported nodes or returns an error tuple in this situation. So far, the easy part, the requirements.

What is the idiomatic Elixir way to stop processing a tree in a recursive function? I plan to handle this with one public function that is called by the user of my module, and the recursive processing is done in a private function. Normally, I would raise an exception and catch this in the public function, either return an ok or an error tuple.

But is this idiomatic?

The ideomatic way here would be to use throw+try/catch, not exceptions. It’s not exceptional, but a expected part of your execution flow.

1 Like

Thanks for the prompt reply! Then I would follow this road.

I would suggest you support passing a closure to your processing function that must return e.g. {:ok, :keep_going} or {:error, :unsupported_node, the_node_variable}. That way your processing function use e.g. Enum.reduce_while or Enum.take_while or some such.

I wouldn’t recommend exceptions or any of the error throwing mechanisms. Elixir has good mechanisms to do an early stop when processing.