1

Hi i am looking for a bit of help with some Clojure code. I have written a function that will take in a list and calculate the qty*price for a list eg. '(pid3 6 9)

What i am looking for is to expand my current function so that it recursively does the qty*price calculation until it reaches the end of the list.

My current function is written like this:

(defn pid-calc [list] (* (nth list 1) (nth list 2)))

I have tried implementing it into a recursive function but have had no luck at all, i want to be able to call something like this:

(pid-calcc '( (pid1 8 5) (pid2 5 6))
 return==> 70

Thats as close as i have came to an answer and cannot seem to find one. If anyone can help me find a solution i that would be great. As so far i am yet to find anything that will compile.

​(defn pid-calc [list]
   (if(empty? list)
    nil
    (* (nth list 1) (nth list 2)(+(pid-calc (rest list))))))

3 Answers 3

2

You don't need a recursive function. Just use + and map:

(defn pid-calc [list]
  (letfn [(mul [[_ a b]] (* a b))]
    (apply + (map mul list))))
Sign up to request clarification or add additional context in comments.

2 Comments

Define list-calc, say as (fn [[_ a b]] (* a b)).
@Thumbnail thanks. OP edited his question and removed the definition of list-calc, so I edited my answer to reflect that.
1

@sloth's answer, suitably corrected, is a concise and fast enough way to solve your problem. It shows you a lot.

Your attempt at a recursive solution can be (a)mended to

(defn pid-calc [list]
   (if (empty? list)
    0
    (let [x (first list)]
      (+ (* (nth x 1) (nth x 2)) (pid-calc (next list))))))

This works on the example, but - being properly recursive - will run out of stack space on a long enough list. The limit is usually about 10K items.

We can get over this without being so concise as @sloth. You might find the following easier to understand:

(defn pid-calc [list]
  (let [line-total (fn [item] (* (nth item 1) (nth item 2)))]
    (apply + (map line-total list))))

1 Comment

Thanks for the help, im pretty much just getting started with clojure. I have only ever really written in OO languages. There is so much more i need to learn, i knew i could simply most of my functions to one liners almost but i dont know what all of the built in methods do yet.
0

reduce fits your scenario quite well:

(def your-list [[:x 1 2] [:x 1 3]])

(reduce #(+ %1 (* (nth %2 1) (nth %2 2))) 0 your-list)

(reduce #(+ %1 (let [[_ a b] %2] (* a b)) 0 your-list)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.