2012-06-28 179 views
2

我想在菜單中顯示項變量的項目使用順序爲宏:循環訪問記錄

(defrecord MenuItem 
    [select-char description]) 

(def menu-items [(MenuItem. "1" "add an expense") 
     (MenuItem. "2" "add an income") 
     (MenuItem. "0" "exit")]) 

(defn display-menu [items] 
    (for [item items] 
    (println (:select-char item)))) 

(defn menu-prompt [items] 
    (display-menu items) 
    (read-val ">>>")) 

(println menu-items) 
(menu-prompt menu-items) 

然而,無非>>>顯示提示。有人可以解釋爲什麼,以及如何顯示項目?

回答

2

這是「懶惰蟲」

用於產生懶惰序列,因爲它是讀取僅被評估的情況。
對顯示菜單的調用只是返回對列表的引用,然後 繼續它的結婚方式沒有做任何事情。

它包裝在一個呼叫doall

 
user> (def a (for [x (range 10)] (println "doing work " x))) 
#'user/a 
user> a 
(doing work 0 
doing work 1 
doing work 2 
doing work 3 
doing work 4 
doing work 5 
doing work 6 
doing work 7 
doing work 8 
doing work 9 
nil nil nil nil nil nil nil nil nil nil) 

,如果你使用的doall或dorun那麼它會立即做的工作。

 
user> (dorun (for [x (range 10)] (println "doing work " x))) 
doing work 0 
doing work 1 
doing work 2 
doing work 3 
doing work 4 
doing work 5 
doing work 6 
doing work 7 
doing work 8 
doing work 9 
nil 
user> (doall (for [x (range 10)] (println "doing work " x))) 
doing work 0 
doing work 1 
doing work 2 
doing work 3 
doing work 4 
doing work 5 
doing work 6 
doing work 7 
doing work 8 
doing work 9 
(nil nil nil nil nil nil nil nil nil nil) 
+0

如果您需要包含帶副作用函數的for循環,則認爲使用doseq更爲經典。 doseq與以下語法具有相同的語法:(doseq [x(range 10)](println x))。我認爲亞瑟表示在多倫/多爾爲了展示正在發生的事情而展示,但最好不要那樣使用它。 – NielsK