Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure - operate on each item in list of lists

I'm working on my first-ever functional program in Clojure. I'm having some issues figuring out how to step through each item in a list, in each list in a list, and operate on it while keeping return values. I'm sure the issue comes from my unfamiliarity with Clojure and functional programming and was hoping someone could explain the best method to do the following:

psuedo-code algorithm:
for each lst in list
   for each item in lst
      return_values.append = do_something(item)

I first tried nesting two doseq functions and then calling my do_something function, which worked to call the function on the item, but didn't save my return values. I then tried a for and cons to an empty list, but was unable to get my return values outside of the for.

Would it be possible/preferable to break the list of lists down first? Could I still get a list of lists of return values?

In the end, I would like the result to be a list of lists of return values to match the input list of lists. If anyone could explain the best method for doing this in Clojure, and why, it would be much appreciated.

like image 355
lost_chayote Avatar asked Nov 15 '15 22:11

lost_chayote


1 Answers

Nested for loop will do the trick:

(for [lst my-list]
  (for [item lst] (do_something item)))

It will take nested list my-list (list of lists) and convert it into another nested list by applying do_something to each element.

In clojure, for returns a list of values already, so there is no need to handle it yourself. Furthermore, since all data structures in clojure are immutable, you can't do this by appending elements to initially empty list with cons.

like image 104
Leonid Beschastny Avatar answered Sep 30 '22 08:09

Leonid Beschastny