killme2008 / defun

A macro to define clojure functions with parameter pattern matching just like erlang or elixir.
Eclipse Public License 1.0
477 stars 20 forks source link

Vizualizing defun #20

Open eyalhrs opened 5 years ago

eyalhrs commented 5 years ago

Hey,

I'd like to use defun to construct a conditional decision tree. Is there any way to visualise it in a tree/graph format?

Thanks

sskorokhodov commented 5 years ago

Hi!

The short answer is - yes, but it's not directly supported by defun. You will have to write some extra code.


One way to do this coming to my mind would be to wrap defun into another macro. The macro then should save the function body into the name symbol's metadata. After that you need a function, which collects this metadata from all the defun definitions in the namespace and recursively analyzes the bodies to find defun calls. That allows you to build a static decision tree.

Obviously, this approach only works when defun is directly called inside other defun's body.

The other problem is to get the decision path after a decision has been made. That could be achieved by updating an execution context on each decision making. That is usually done by updating a dynamic var, atom, or passing a context directly to the function. The macro from the first step can help with it as well.

As you could notice, both steps are not supported by defun directly, but both rely on the structure of its arguments and the ability to define each level of a decision tree separately.

I would be very happy if someone could suggest an easier solution, though :)

eyalhrs commented 5 years ago

Thanks for the fast response. Regardless of visualisations, do you have an example for using defun as the basis for implementing a decision tree? I have a complex conditional flow that I need to rewrite, and it seems to me defun can be a good choice. Thanks again

sskorokhodov commented 5 years ago

No examples, sorry.

But I can’t imagine any other way of using defun than just defining a bunch of functions and nesting them as you would do with defn :)

I think Prolog could be the right choice for the task. There are a few articles about visualizing decision trees in Prolog (because the primary purpose of the language is to build and solve decision trees). That’s what I found after a short googling.

The nearest alternative in Clojure world is Datalog. Maybe someone has already solved your problem for it.