[英]Building a string in Clojure with recursion
I need to generate a random char and build a string and only stop when my string contains the newly generated char. 我需要生成一个随机字符并构建一个字符串,并且仅在我的字符串包含新生成的字符时才停止。
(defn rand-char [len]
(apply str (take len (repeatedly #(char (+ (rand 26) 65))))))
(def random-string
(loop [x (rand-char 1)
result []]
(if (some #(= x %) result)
(apply str (conj result x))
(recur (conj result x) (x (rand-char 1))))))
I am getting 我正进入(状态
java.lang.String cannot be cast to clojure.lang.IFn
rand-char
returns a string
but in (x (rand-char 1))
you're attempting to call x
as a function, hence the error. rand-char
返回一个string
但是在(x (rand-char 1))
您试图将x
作为函数调用,因此出错。 You only need to call rand-char
to generate the next random string to try. 您只需要调用
rand-char
来生成下一个随机字符串即可尝试。 The arguments to recur
should be in the same order as those declared in the loop
so yours are in the wrong order: 要
recur
的参数应与loop
声明的顺序相同,因此您的顺序错误:
(recur (rand-char 1) (conj result x))
something like this does it serve you? 这样的事情对您有用吗?
(defn random-string []
(loop [x (rand-char 1)
result []]
(if (.contains result x)
(apply str result)
(recur (rand-char 1) (conj result x)))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.