How to implement a For loop in Clojure

后端 未结 2 1743
一生所求
一生所求 2020-12-24 12:27

I\'d like to implement this little code in Clojure, but I am struggling:

struct mystruct {
   int id;
   int price;
}         


        
2条回答
  •  时光说笑
    2020-12-24 13:05

    Jeremy's answer is good for how to do a for loop in idiomatic Clojure.

    If you really want an imperative-style for loop in Clojure, you can create one with this macro:

    (defmacro for-loop [[sym init check change :as params] & steps]
     `(loop [~sym ~init value# nil]
        (if ~check
          (let [new-value# (do ~@steps)]
            (recur ~change new-value#))
          value#)))
    

    Usage as follows:

    (for-loop [i 0 (< i 10) (inc i)] 
      (println i))
    

提交回复
热议问题