我正在尝试使用for-macro显示menu-items变量中的项目:
(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)
然而,只有>>>显示提示。有人可以解释为什么会这样,以及如何显示这些项目吗?
答案 0 :(得分:2)
这是“懒虫”的案例
用于生成一个惰性序列,该序列仅在读取时进行评估 对display-menu的调用只返回对列表的引用然后 继续它的结婚方式没有做任何事情。
将其包裹在对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)