10

我正在为我的 Clojure 程序编写一个从键盘读取用户输入的函数。如果用户输入了无效的输入,则会警告用户,然后再次提示。在像 Python 这样的语言中使用程序风格时,我会做这样的事情:

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

我在 Clojure 中能想到的最好的方法是:

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

这可行,但它是多余的并且看起来很冗长。有没有更多的 Lispy/Clojurey 方式来做到这一点?

4

2 回答 2

21
(defn input []
   (println "What is your decision?")
   (if-let [v (valid? (read-line))]
      v
      (do
         (println "That is not valid")
         (recur)))
于 2010-11-23T01:10:32.387 回答
8

将 println/read-line 组合分解为 get-line 函数:

(defn get-input [prompt]
  (println prompt)
  (read-line))

(defn get-validated-input []
  (loop [input (get-input "What is your decision?")]
    (if (valid? input)
      value
      (recur (get-input "That is not valid.\nWhat is your decision?")))))

这基本上就是您的 Python 版本所做的;不同之处在于 get-input 是 Python 内置的。

于 2010-11-23T19:13:42.120 回答