Terry Masters
Terry Masters

Reputation: 21

Clojure cond or if?

Currently I am programming a map that will take an amount of money from one id and transfer it to another but whenever I add an if or cond statement to make sure that they have enough in their balance I keep getting a sending too many arguments error. if I use cond It says that cond requires an even number of forms. Any help would be appreciated

Code:

 (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
            ))))))))

Upvotes: 0

Views: 1193

Answers (1)

Davyzhu
Davyzhu

Reputation: 1109

It's not about cond or if, but it's on "how to group multiple s-exps into one and evaluate them sequentially".

Use do as in:

(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"))))))

Upvotes: 2

Related Questions