首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将clojure代码放入循环中

将clojure代码放入循环中
EN

Stack Overflow用户
提问于 2010-09-20 06:34:20
回答 3查看 423关注 0票数 1
代码语言:javascript
复制
(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平方为100),并获得我得到的多少次点击作为返回值。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-09-20 06:46:24

如果理解正确的话,我想这就是你想要的。

代码语言:javascript
复制
(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)))))))
票数 0
EN

Stack Overflow用户

发布于 2010-09-20 17:55:54

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

代码语言:javascript
复制
(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)))))))  
票数 0
EN

Stack Overflow用户

发布于 2011-01-22 19:19:06

代码语言:javascript
复制
(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}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3747763

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档