首先,我有一个像这样的Mysql表:
create table t (id int(11) PRIMARY KEY unsigned NOT NULL AUTO_INCREMENT, name varchar(20), age int(10));
我定义了一个在t中创建一行的函数:
(require '[honeysql.core :as sql]) (defn do-something [] (sql/query {:insert-into :t :values [{:name "name1" :age 10}]}) (> 3 (rand-int 5)))现在我想运行这个函数,直到它返回true但最多N次。
这个take-times代码是错误的,因为重复将eval do-something函数一次,然后构造惰性序列。
(defn take-times [] (some true? (repeat 5 (do-something))))无论什么do-something回归,这个take-times2将评估5次。
(defn take-times2 [] (some true? (for [i (range 5)] (do-something))))如果我不使用递归函数和宏,我该怎么办?
First of All, I have a Mysql table like this:
create table t (id int(11) PRIMARY KEY unsigned NOT NULL AUTO_INCREMENT, name varchar(20), age int(10));
I define a funtion that will create a row in t:
(require '[honeysql.core :as sql]) (defn do-something [] (sql/query {:insert-into :t :values [{:name "name1" :age 10}]}) (> 3 (rand-int 5)))And now I want to run this function until it return true but at most N times.
This take-timescode is wrong because repeat will eval the do-something function one time and then structure the lazy sequence.
(defn take-times [] (some true? (repeat 5 (do-something))))This take-times2 will eval the do-something 5 times no matter what the do-something return.
(defn take-times2 [] (some true? (for [i (range 5)] (do-something))))What should I do if i do not use recursion function and macro?
最满意答案
这应该工作:
(->> (repeatedly do-something) (take 5) (some true?))更新(04.11.2014):
由于repeatedly实际允许可选的长度参数,这也很好:
(some true? (repeatedly 5 do-something))例
(defn do-something [] ;; 20% chance of true (let [ret (rand-nth [true false false false false])] (prn 'hello ret) ret)) (defn run [] (->> (repeatedly do-something) (take 5) (some true?))) (run) ;; hello false ;; hello false ;; hello true ;; => true (run) ;; hello false ;; hello false ;; hello false ;; hello false ;; hello false ;; => nilThis should work:
(->> (repeatedly do-something) (take 5) (some true?))Update (04.11.2014):
Since repeatedly actually allows for an optional length parameter, this is also fine:
(some true? (repeatedly 5 do-something))Example
(defn do-something [] ;; 20% chance of true (let [ret (rand-nth [true false false false false])] (prn 'hello ret) ret)) (defn run [] (->> (repeatedly do-something) (take 5) (some true?))) (run) ;; hello false ;; hello false ;; hello true ;; => true (run) ;; hello false ;; hello false ;; hello false ;; hello false ;; hello false ;; => nil更多推荐
发布评论