0

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

2 Answers 2

2

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))
Sign up to request clarification or add additional context in comments.

3 Comments

@rake-write-code - Do you want random-string to be a function? At the moment you're using def so it's being evaluated to a vector. (random-string) is trying to call the vector as a function. Vectors are functions from an index to the corresponding value e.g. ([1 2 3] 0) => 1 so you get the error because you haven't supplied enough arguments. It looks like you should defined random-string using defn e.g. (defn random-string [] ...).
Hi @lee, Thanks for all the pointers, it is supposed to be a method and I've been able to run it by just passing 0 as a parameter. I have been able to print a correct string but I want it returned instead and it evaluates to a null reference. (def random-string (loop [x (rand-char 1) result ""] (if (.contains result x) (println (str result x)) (recur (rand-char 1) (str result x))))) but I don't want to print it but instead return it. just returning (str result x) says java.lang.String cannot be cast to clojure.lang.IFn .
Thanks for your help @lee, I got it. I just needed to pass a vector to the function when I define it.
1

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)))))

1 Comment

Thanks for your help. I have already accepted Lee's answer, I have since also opted to build result directly as a string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.