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. You only need to call rand-char
to generate the next random string to try. The arguments to recur
should be in the same order as those declared in the loop
so yours are in the wrong order:
(recur (rand-char 1) (conj result x))