Cycle improvement

I wrote a function that tries to get y / n (yes / no) response from the user interactively. It checks if the answer is valid, and if not, it asks the user again:

(defn get-valid-answer [question]
   (println  question)
   (loop []
     (let [ans (.trim (read-line))]
        (if (#{"y" "n"} ans)
            ans
            (do (println "Please answer \"y\"[yes] or \"n\"[no] only!")
                (recur) )))))

The above version with loop-recur does the job, but I feel that there should be a better (more functional) way to do this. I would prefer that the read call be made only once. Can someone suggest an alternative version that does not use loop-recur in this scenario, but perhaps using the (Clojure built-in) macro instead?

+5
source share
1 answer

, , , . , .

, .

(defn ask []
  (println "Please answer \"y\"[yes] or \"n\"[no]:")
  (.trim (read-line)))

(defn get-valid-answer [question]
  (println question)
  (->> (repeatedly ask)
       (filter #{"y" "n"})
       (first)))

"ask" let, .

+7

All Articles