Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lispy way to read user input from the keyboard in Clojure?

I am writing a function for my Clojure program that reads user input from the keyboard. If the user enters invalid input, the user is warned and then prompted again. When using a procedural style in a language like Python, I would do something like this:

while 1:
    value = input("What is your decision?")
    if validated(value):
        break
    else:
        print "That is not valid."

The best I can come up with in Clojure is this:

(loop [value (do
               (println "What is your decision?")
               (read-line))]
  (if (validated value)
    value
    (recur (do
             (println "That is not valid.")
             (println "What is your decision?")
             (read-line)))))

This works, but it is redundant and seems verbose. Is there a more Lispy/Clojurey way to do this?

like image 743
davidscolgan Avatar asked Nov 23 '10 00:11

davidscolgan


1 Answers

(defn input []
   (println "What is your decision?")
   (if-let [v (valid? (read-line))]
      v
      (do
         (println "That is not valid")
         (recur)))
like image 76
dnolen Avatar answered Nov 18 '22 11:11

dnolen