Search code examples
clojure

How to retrieve element by key after using instaparse in clojure?


I am trying to make a compiler for a school project. I am a beginner in clojure. I have done a simple program (interpreting-lang-if) which can parse a string using instaparse and return a vector like this :

[:LangIF [:before_if "676767; "] [:condition_expression "0"] 
[:statements_OK "1; 2;"] [:statements_NOK "3+4;"] [:after_if ""]]

How can I get the "before_if" element from the list?

I tried to understand the get function but I must have minsunderstood something in the usage of the function.

Here is some code :

(prn (interpreting-lang-if "676767; if (0) {1; 2;}else{3+4;};"))
(get (interpreting-lang-if "676767; if (0) {1; 2;}else{3+4;};") :before_if)
(get :before_if (interpreting-lang-if "676767; if (0) {1; 2;}else{3+4;};"))

The expected output is supposed to be "676767" instead of nil.

Thanks for your help.


Solution

  • If you dont know the exact position of the item:

    (->> [:LangIF [:before_if "676767; "] [:condition_expression "0"]
          [:statements_OK "1; 2;"] [:statements_NOK "3+4;"] [:after_if ""]]
         (tree-seq vector? rest)
         (filter vector?)
         (filter (comp (partial = :before_if) first))
         (first)
         (second))
    

    or if you do and would like to use specter:

    (let [A [:LangIF [:before_if "676767; "] [:condition_expression "0"]
           [:statements_OK "1; 2;"] [:statements_NOK "3+4;"] [:after_if ""]]]
        (select [1 1] A))
    

    or with simple get:

    (let [A [:LangIF [:before_if "676767; "] [:condition_expression "0"]
           [:statements_OK "1; 2;"] [:statements_NOK "3+4;"] [:after_if ""]]]
        (get (get A 1) 1))