Clojure cond还是?

时间:2016-03-02 02:34:45

标签: clojure

目前我正在编制一个地图,它将从一个ID中获取一定数量的金钱并将其转移到另一个ID,但每当我添加if或cond语句以确保它们有足够的余额时我会继续发送太多参数错误。如果我使用cond它说cond需要偶数个形式。任何帮助将不胜感激

代码:

 (defn transfer[ledger from-id to-id amt]
    (dosync
        (let [from-id (get @ledger from-id)]
        (let [to-id (get @ledger to-id) ]
            (if from-id 
                (if to-id
                    (let [bal1 (get from-id :balance)]
                    (let [bal2 (get to-id :balance)]
                        (cond (< amt bal1)
                            (alter bal1 - amt)
                            (alter bal2 + amt)
                        :else "Too much"

                    )       
            nil
                nil
            ))))))))

1 个答案:

答案 0 :(得分:2)

这不是关于condif,而是关于“如何将多个s-exp组合成一个并按顺序评估它们”。

使用do,如下所示:

(defn transfer[ledger from-id to-id amt]
  (dosync
   (let [from-id (get @ledger from-id)
         to-id (get @ledger to-id)]
     (if (and from-id to-id)
       (let [bal1 (:balance from-id)
             bal2 (:balance to-id)]
         (if (< amt bal1)
           (do
             (alter bal1 - amt)
             (alter bal2 + amt))
           "Too much"))))))