将clojure代码放入循环中

时间:2010-09-19 22:34:20

标签: clojure

(def throws 10)

(defn r-squared [x y] 
 (+ (* (- 0.5 x) (- 0.5 x)) 
    (* (- 0.5 y) (- 0.5 y))))

(loop [hits 0]
  (let [x (rand)
        y (rand)]
    ; still inside the let
    (if (< (r-squared x y) 0.25) ;is it a hit or not? if not, try again
        (recur (inc hits)) 
        (* 4 (/ hits throws)))))  

我让代码工作并运行,直到if条件为真。我怎样才能重写它,所以它需要X作为参数并运行X次?

我基本上想要调用(r-squared 100)并获得多少次点击作为返回值。

3 个答案:

答案 0 :(得分:0)

我认为这是你想要的,如果正确地提出问题。

(defn test [n]
  (loop [hits 0 n n]
    (let [x (rand)
          y (rand)]
      (if (< n 0)
          hits ;// you can put (* 4 (/ hits throws)) here
          (if (< (r-squared x y) 0.25)
              (recur (inc hits) (dec n))
              (recur hits (dec n)))))))

答案 1 :(得分:0)

没有评估它,所以parn可能有些错误。

(def throws 10)

(defn r-squared [x y] 
 (+ (* (- 0.5 x) (- 0.5 x)) 
    (* (- 0.5 y) (- 0.5 y))))


 (defn test-r-squared [n] 
  (loop [hits (int 0) n (int n)]
   (let [x (rand)
         y (rand)]
    ; still inside the let
    (if (< n 0)
       (* 4 (/ hits throws))
       (if (< (r-squared x y) 0.25) ;is it a hit or not? if not, try again
         (recur (inc hits) (dec n)) 
         (recur hits (dec n)))))))  

答案 2 :(得分:0)

(defn r-squared [x y] 
 (+ (* (- 0.5 x) (- 0.5 x)) 
    (* (- 0.5 y) (- 0.5 y))))

(defn hit[]
  (let [x (rand) y (rand)]
    (< (r-squared x y) 0.25)))


(frequencies (for [i (range 1000)] (hit))) ; {true 787, false 213}