Welcome! Please see the About page for a little more info on how this works.

0 votes
in Clojure by

How can I parse the abstract syntax tree from a function? For instance, given

 (defn f [x]
     (/ (- 1.0 (Math/exp (- x))) 2.0))

Is there some way to parse it into a datastructure like a list:

[:op "/" [:op "-" 1.0 [:op "Math/exp" [:op "-" x]]] 2.0]


P.S.: I understand that this is almost the same . I am trying to learn Clojure and this seems to be trivial problem, but I can't find a solution.

1 Answer

+2 votes

Hello! There is a useful library for such tasks called tools.analyzer that would be of service. The link is https://github.com/clojure/tools.analyzer

Thanks! This comes pretty close, so far I haven't found a way though to make it do what I want. Specifically, I want to just plug in a function name into a parse function, e.g., `(parse f)`, and receive the AST for f as `tools.analyzer` does it.
You can get pretty close to that behavior by combining tools.analyzer with the clojure.repl/source function.
Perfect, thanks! Found a work-around that uses clojure.repls/source-fn here: clojureverse.org/t/how-to-print-a-source-of-a-function-passed-as-a-parameter/6160/4