clojure - if-let语法

dag*_*da1 1 clojure clojurescript

我正在尝试重构此代码以使用if-let:

om/IWillMount
  (will-mount [_]
    (go (while true
          (if (om/get-state owner :is-loaded)
            (let [updated-world (<! (update-world (:dimensions opts) (:world @data)))]
              (om/transact! data #(assoc % :world updated-world))
              (swap! app-state assoc :world updated-world))
            (let [world (<! (get-world (:dimensions opts)))]
              (om/set-state! owner :is-loaded true)
              (om/transact! data #(assoc % :world world))
              (swap! app-state assoc :world world)))
          (<! (timeout (:poll-interval opts))))))
Run Code Online (Sandbox Code Playgroud)

到目前为止,我试过这个:

om/IWillMount
  (will-mount [_]
    (go (while true
          (if-let [world (om/get-state owner :is-loaded)]
                    (<! (update-world (:dimensions opts) (:world @data)))
                    (<! (get-world (:dimensions opts)))
              (om/set-state! owner :is-loaded true)
              (om/transact! data #(assoc % :world world))
              (swap! app-state assoc :world world))
          (<! (timeout (:poll-interval opts))))))
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误:

引起:java.lang.IllegalArgumentException:if-let在web-game-of-life.app:58中绑定向量后需要1或2个表单

A. *_*ebb 5

if-let不适用......

if-let宏在这里不适用.在a中if-let,结合形式的结果用作测试.它浓缩代码就像

(let [world (get-world ...)]
   (if world
     (do-something-with world)
     (do-something-else)))
Run Code Online (Sandbox Code Playgroud)

例如,如果在没有检索get-worldnil世界时返回.

在您的案例中,您要测试的值与要绑定的值不同.您正在测试,(om/get-state owner :is-loaded)但没有使用结果.

......但可以考虑重复的代码

你的代码确实有重复,所以有一个保理机会.首先,将第一个绑定符号的相同代码更改为与第二个绑定,并标记重复的行.

          (if (om/get-state owner :is-loaded)
            (let [world (<! (update-world (:dimensions opts) (:world @data)))]
(1)           (om/transact! data #(assoc % :world world))
(2)           (swap! app-state assoc :world world))
            (let [world (<! (get-world (:dimensions opts)))]
              (om/set-state! owner :is-loaded true)
(1)           (om/transact! data #(assoc % :world world))
(2)           (swap! app-state assoc :world world)))
Run Code Online (Sandbox Code Playgroud)

现在考虑反转iflet

(let [world (if (om/get-state owner :is-loaded) 
              (<! (update-world (:dimensions opts) (:world @data)))
              (do
                (om/set-state! owner :is-loaded true) 
                (<! (get-world (:dimensions opts)))))] 
  (om/transact! data #(assoc % :world world)) 
  (swap! app-state assoc :world world))
Run Code Online (Sandbox Code Playgroud)