2010-11-23 72 views
10

我正在爲我的Clojure程序編寫一個函數,用於從鍵盤讀取用戶輸入。如果用戶輸入無效的輸入,則會警告用戶,然後再次提示。當像Python語言使用過程風格,我會做這樣的事情:Lispy從Clojure中的鍵盤讀取用戶輸入的方式?

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的方式來做到這一點?

回答

21
(defn input [] 
    (println "What is your decision?") 
    (if-let [v (valid? (read-line))] 
     v 
     (do 
     (println "That is not valid") 
     (recur))) 
8

分解出的println /讀取線組合成一個get-線功能:

(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中的。