我正在为我的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方法来做到这一点?
答案 0 :(得分:21)
(defn input []
(println "What is your decision?")
(if-let [v (valid? (read-line))]
v
(do
(println "That is not valid")
(recur)))
答案 1 :(得分: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。