mik*_*era 2 design-patterns functional-programming clojure
我决定尝试在Clojure中编写一个模拟程序(作为概念证明),其中:
这意味着我可以编写更新函数,如:
(defn example-update-function [old-state]
(let [state (atom old-state)]
(swap! state some-other-update-function-1)
(if (some-condition @state)
(swap! state some-conditional-update-function))
(swap! state some-other-update-function-2)
(reset! state (some-function @state some-other-param))
@state))
Run Code Online (Sandbox Code Playgroud)
这种方法似乎有效但下面给出了两个值得关注的原因:
有更好/更优雅的方法吗?
你可以像这样写:
(defn change-when "If (test val) is truethy, returns (fun val), else returns val" [val test fun] (if (test val) (fun val) val)) (defn example-update-function [old-state] (-> old-state some-other-update-function-1 (change-when some-condition some-conditional-update-function) some-other-update-function-2 (some-function some-other-param) identity))
可能是在monad之路的中途......