retrying something 3 times before throwing an exception - in clojure

后端 未结 4 1294
旧时难觅i
旧时难觅i 2021-02-10 04:58

I don\'t know how to implement this piece of Python code in Clojure

for i in range(3):
    try:
        ......
    except e:
        if i == 2:
            raise         


        
4条回答
  •  有刺的猬
    2021-02-10 05:34

    You can do like this:

    (defn retry
      "Tries at most n times, return first try satisfying pred or nil"
      [times pred? lazy-seq]
      (let [successful-trial (drop-while (complement pred?) (take times lazy-seq))]
        (if (empty? successful-trial)
            nil
            (first successful-trial))))
    

    Then you could use the function as such:

    (when-not (retry 3 pos? (repeatedly #(rand-nth [-1 -2 -3 2 1]))
        (throw (Exception. "my exception message"))
    

    This would try at most three times to take a positive number at random from the vector and if it doesn't succeed, throws an exception.

提交回复
热议问题