Macro for supports Loop
Next we will continue with the preceding XML example to demonstrate how to use for to traverse the sequence returned by XML-seq.
user=> (for [x r] (println "^" x))(^ {:tag :service, :attrs nil, :content [{:tag :mongodb, :attrs nil, :content [{:tag :uri, :attrs nil, :content [localhost]}]} {:tag :socket, :attrs nil, :content [{:tag :port_number, :attrs nil, :content [7777]} {:tag :login_timeout, :attrs nil, :content [200]} {:tag :check_timeout, :attrs nil, :content [200]}]}]}^ {:tag :mongodb, :attrs nil, :content [{:tag :uri, :attrs nil, :content [localhost]}]}nil ^ {:tag :uri, :attrs nil, :content [localhost]}nil ^ localhostnil ^ {:tag :socket, :attrs nil, :content [{:tag :port_number, :attrs nil, :content [7777]} {:tag :login_timeout, :attrs nil, :content [200]} {:tag :check_timeout, :attrs nil, :content [200]}]}nil ^ {:tag :port_number, :attrs nil, :content [7777]}nil ^ 7777nil ^ {:tag :login_timeout, :attrs nil, :content [200]}nil ^ 200nil ^ {:tag :check_timeout, :attrs nil, :content [200]}nil ^ 200nil nil)
Print a ^ symbol before each sequence element to facilitate resolution.
Add conditional filtering. For example, if the tag is MongoDB
user=> (for [x r :when (= :mongodb (:tag x))] x)({:tag :mongodb, :attrs nil, :content [{:tag :uri, :attrs nil, :content ["localhost"]}]})user=>
Square brackets after for are a vector, r is the sequence returned by XML-seq, and X is the element in sequence. The next element is automatically obtained for each loop: When (...) is a condition judgment statement. When when (...) returns true, the expression after the vector is executed. Because it is only X, the element of this symbol condition is used as the return value of.
: When will not stop the loop from ending early, but: While is different.
If the value of while (...) is false, the loop exits immediately.
Therefore, an empty list is returned below.
user=> (for [x r :while (= :mongodb (:tag x))] x)()
Because the tag value of the first element is service, which is not the same as MongoDB, the loop is stopped.