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

0 votes
in Collections by

I'm a newbie in Clojure and I'm struggling with looping through data in data structures.

I have a list that looks like this : (list1)
([1 (item1 item2 item3)]
[2 (item21 item22 item33)])

And another one that looks like this: (list2)
([1 (rec1 rec2 rec3)]
[2 (rec21 rec22 rec33)])

And the last one is: (list3)
([1 (1 1 3)]
[2 (2 2 3)])

Now, I have to loop into list3 and create a new collection that replaces the 1 (in my list3) by "item1" and replaces the second 1 (in my list3 too) by "rec1" ... and so on for all the vectors in list3...

The three lists have the exact same number of records.

My third list should look like :
([1 (item1 rec1 3)]
[2 (item21 rec22 3])

Any idea how to proceed?

1 Answer

0 votes
selected by
Best answer

Hey again!

Your question is prescriptive. There is an assumption that you have to store your data as ([1 (item1 item2 item3)] [2 (item21 item22 item33)]) and from what I've seen of your coding yesterday you have probably chosen an inappropriate data structure (might have used [{:id 1 :item shoes :price 14.96}, {:id 2 :item milk :price 1.98}] myself). The approach changes depending on whether the id is a true id and unique to each item. I'd be trying to use the clojure.set functions (https://clojure.github.io/clojure/clojure.set-api.html) as they are good for this sort of operation where you really want to clojure.set/join, clojure.set/select then clojure.set/project.

That aside, I think the transform you are asking for is map, which is a popular function and you can see documented @ https://clojuredocs.org/clojure.core/map:

 (fn [x y z] [(first x) 
              (list (first (second x)) 
                    (first (second y)) 
                    (nth (second z) 2))])

That doesn't give you exactly what you asked for, I can't tell why you picked rec1 for 1 but rec22 for 2.

I didn't choose the data structure, it was given this way in the instructions.
To answer the question, the third list is like a merge of the 2 lists 1 & 2.
So, for the first record in list3 :
1 = id of the record
(1 1 3) = 1: id of the record of the first list | 1: id of the record of the second list | 3 : random number that doesn't have to be changed in the new collection.
Ok. The popular advice is to think about this problem as building a new 4th list with elements of all 3 existing lists.

A `map` should still be what you asked for, you'll have to adjust the applyed function until it does what you want.
Thank you very much... After the adaptation and many tests, I figured it out.
Appreciate the help! :)