CS456
CS456

Reputation: 117

Function not being evaluated in let block

I've written a little recursive function, however, if i include the recursive bit in the let block it throws an unsuported binding error.

The code:

(defn total-weight [parcel cost]
 "Calculate the total route cost"
  (if (not(empty? parcel))
     (let [ first-parcel (first parcel)
        weight (:weight first-parcel)
        parcel-two (rest parcel)
       (total-weight parcel-two (+ cost weight))
      cost])))


(total-weight task5 0)

The error:

CompilerException java.lang.Exception: Unsupported binding form: (total-weight parcel-two (+ cost weight)), compiling:(/private/var/folders/2h/7b4v1ls11mjf_n5hb6mwngl40000gn/T/form-init2186446380943426996.clj:4:6) 

Any ideas?

Upvotes: 0

Views: 73

Answers (2)

amalloy
amalloy

Reputation: 92117

While this is a fine exercise to practice recursive thinking, note as an aside that the "best" way to implement this as an experienced Clojure programmer would be:

(apply + (map :weight task5))

So simple it doesn't even need a function defined for it.

Upvotes: 2

tony
tony

Reputation: 67

Your function should be like this:

(defn total-weight [parcel cost] "Calculate the total route cost" 
   (if (not (empty? parcel))
     (let [first-parcel (first parcel)
           weight (:weight first-parcel)
           parcel-two (rest parcel)]
       (total-weight parcel-two (+ cost weight))
     cost)))

let in bind should be like

(let [x1 x2] (print x1))

your ] is in the wrong place.

Upvotes: 1

Related Questions