本文介绍了如何在Clojure中创建一个随机数的惰性序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建一个懒惰的随机数序列?

How can I create a lazy sequence of random numbers?

我当前的代码:

(import '(java.util Random))

(def r (new Random))
(defn rnd [_]
    (.nextInt r 10))

(defn random-numbers [max]
    (iterate #(.nextInt r max) (.nextInt r max)))

(println (take 5 (random-numbers 10)))

执行它会引发异常:

这是一种完全错误的方法,因为我正在使用状态,即r是java.util.Random的实例,还是仅仅是nooby语法错误?

Is this a completey wrong approach, because I am using state, namely r is an instance of java.util.Random, or is it just a nooby syntax error?

我只是研究自己的clojure,所以请忍受我:).

I just studing clojure on myself, so please bear with me :) .

推荐答案

重复非常适合重复运行函数并将结果收集在seq中

repeatedly is great for repeatedly running a function and gathering the results in a seq

user> (take 10 (repeatedly #(rand-int 42)))
(14 0 38 14 37 6 37 32 38 22)

对于您的原始方法,

:iterate接受一个参数,将其提供给一个函数,然后接受该结果,然后将其传递回相同的函数.我在这里不是您想要的,因为您使用的函数不需要任何参数.您当然可以为其指定一个占位符并使其生效,尽管重复可能更合适.

as for your original approach: iterate takes an argument, feeds it to a function and then takes the result of that and passes it back to the same function. I't not quite what you want here because the function you are using doesn't need any arguments. You can of course give it a placeholder for that argument and get it working, though repeatedly is likely a better fit.

(defn random-numbers [max]
  (iterate (fn [ignored-arg] (.nextInt r max)) (.nextInt r max)))
#'user/random-numbers

user> (println (take 5 (random-numbers 10)))
(3 0 0 2 0)

这篇关于如何在Clojure中创建一个随机数的惰性序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 14:38