Welcome! Please see the About page for a little more info on how this works.

0 votes
in Collections by
retagged by

It's me again. I followed up on the previous answers that have been posted on my questions to do another operation but I don't get exactly what I want.
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: (36.5 + 11.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))))
(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 :') .

1 Answer

0 votes
edited by

So I think the best advice here would be to reorganize your data structures a bit.
I chose to model this as sets of maps:

(def products
  #{{:id 1
    :product_name "candies"
    :price 6.5}
   {:id 2
    :product_name "sweets"
    :price 1.75}
   {:id 3
    :product_name "jam"
    :price 2.99}
   {:id 4
    :product_name "gum"
    :price 1.25}})

(def customers
  #{{:id 1
    :name "Sara"
    :product "candies"
    :quantity 3}
   {:id 2
    :name "Joe"
    :product "jam"
    :quantity 3}
   {:id 3
    :name "Sara"
    :product "gum"
    :quantity 1}})

What's neat about that approach is that you can use clojure.set to manipulate this:

(require '[clojure.set :as set])
;' needed to please the formatter

(->> (set/join customers products {:product :product_name})
     (set/select #(= (:name %) "Sara"))
     (map (fn [{:keys [price quantity]}] (* price quantity)))
     (reduce + 0))

I didn't make this into a function, but I guess you get the gist of it.