Search code examples
clojuremaps

Addition/Multiplication operations on loop


I'm a newbie to Clojure and need some help with my code. Here's the situation:

My first table (products) looks like : (product_name price)

([1 (candies 6.5)] 
 [2 (sweets 1.75)]
 [3 (jam 2.99)] 
 [4 (gum 1.25)])

My first table (products) looks like : (customer_name product_name quantity)

([1 (Sara candies 3)] 
 [2 (Joe jam 3)]
 [3 (Sara gum 1)])

What I'm trying to do is if i type for example Sara, I'll get the sum of the sales made by Sara, which means: (3 * $6.5 + 1 * $1.25) = $20.75 (in this case)

I'm fine for the input part (I get the name of the customer as an input from the terminal) However, my code:

(defn sales_prices_with_cond [name_cus] (map
 (fn [y z]
   (if (= (str name_cus) (str (nth (first z) 1)))
   list (* (Double. (nth (second y) 1)) (Integer/parseInt (nth (second z) 2))))
   )
products 
sales))
(println (reduce + sales_prices_with_cond "Sara"))

Gives me the sum of ALL the sales*quantities. It's like the condition is skipped or maybe not well written ... I also tried with (some) and got the same result...

Please Help :') .


Solution

  • Your tables don't look like valid Clojure code which makes it difficult to help you - are they strings? I would transform the first one into a map of the form: (def prices {"candies" 6.5}) ;etc

    Your second table would be something like: (def sales [["sarah" "candies" 3]]) ;etc

    And then your main function:

    (defn sales-by-customer [name-cus]
      (->> sales
           (filter #(= (first %) name-cus))
           (map #(* (last %) (prices (second %)))
           (reduce +)))