我有一个在游戏中运行的I/O函数列表,但是需要从do中间的某个函数中收集值。
(defn setup-steps [game-state]
(do (io/clear-screen)
(print-welcome-message)
(initial-setup) ;; value to be collected
(io/clear-screen)
(io/print-board game-state)))有什么聪明的方法可以从do中间的某个地方返回值吗?
接下来,我使用setup-steps的返回值更新一个原子,如下所示:
(defn game-loop [game]
(while (:game-in-progress? @game)
;; Here is where I am using the results
(->> (s-io/setup-steps @game) (state/updater game))
(while (:game-in-progress? @game)
(->> (m-io/turn-steps @game) (state/updater game)))
(->> (eg-io/end-game-steps @game) (state/updater game)))
(eg-io/exit-game))哪里
(defn updater
"Updates the game state.
This is the only place where the game atom is modified."
[game update-params]
(swap! game merge update-params))我相信您可以为此编写一个宏,但我还不太了解宏。
也许我想错了.道指swap! it setup-steps是否更有习性?
发布于 2018-01-26 19:49:39
有什么原因不能在let中分配结果并在函数结束时返回呢?
(defn setup-steps [game-state]
(io/clear-screen)
(print-welcome-message)
(let [v (initial-setup)] ;; value to be collected
(io/clear-screen)
(io/print-board game-state)
v))编辑:去掉Ryan提到的多余的do。
发布于 2018-01-26 22:36:43
从根本上说,实现这一目标的唯一方法是使用let,如clartaq所示。但是,如果你觉得这令人讨厌,有很多种方法,你可以用一个宏来包装它,让它看起来更漂亮,并且更清楚你在做什么。这里是最简单的一个,我喜欢称之为returning
(defmacro returning [x & more]
`(let [x# ~x]
(do ~@more)
x#))
(defn foo []
(x)
(y)
(returning (z)
(a)
(b)))当然,do in returning是多余的,但我认为强调more只用于副作用的评估仍然是有用的。
https://stackoverflow.com/questions/48468341
复制相似问题