5

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.

3 Answers 3

5

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.

7
  • 2
    also works in a single for: (for [row my-list, cell row] (...))
    – cfrick
    Nov 16, 2015 at 8:39
  • @cfrick single for will generate flattened list, containing all elements, not a nested one. Nov 16, 2015 at 12:31
  • True, and that was, what I thought OP wanted - or at least how i interpreted the return_values.append = f(item)
    – cfrick
    Nov 16, 2015 at 12:54
  • @cfrick I aree that OP's question is a little bit confusing here, because he asks for a nested list, but includes pseudocode example to get a flattened one. Nov 16, 2015 at 12:58
  • @LeonidBeschastny Yes, sorry, my pseudocode is wrong. I do want my results in a list structured exactly as my input list was structured. You say that for returns a list of values already, but that data structures are immutable, so it can't be making the changes in place (replacing each value of input with the result of the function), can it? So how do I access the return values from a for? Nov 16, 2015 at 20:13
0

If you have a deeply nested list and you want to keep its structure, but transform the values, you can use clojure.walk/postwalk to operate on each value, e.g.:

(def nested '(1 (2 3 (4 5)) 6))

(defn transform-values [coll f]
  (clojure.walk/postwalk #(if (not (list? %))
                            (f %)
                            %)
                         coll))

(transform-values nested inc)

=> (2 (3 4 (5 6)) 7)

You can, of course, pass any function to transform-values.

4
  • Thanks for the response! I tried this, but still get nil when I try to do anything with my values. I'm using something along the lines of (def my_vals (transform-values my_coll my_func)). Am I going about getting those values wrong? Nov 16, 2015 at 0:01
  • Okay, I figured out some of the issue is that I have a sequence, not a list, so I exchanged list? for seq? and now get my values, but it looks like I'm still passing whole lists into my function. My data is organized as [ [ a b c] [d e f] [g h i] ], so it's a list containing several lists, and I need my function to operate on a, b, c, d, e, etc. Can I nest walks to achieve this? Nov 16, 2015 at 0:09
  • Vector is not a seq. (seq? []) => false Nov 16, 2015 at 16:03
  • I updated the code to provide an alternative. For sure you can have an or there to support seqs, lists and vectors. Nov 16, 2015 at 16:07
0

This can be done as a simple recursive walk. The first implementation that comes to mind for this would be the following for sequences:

(defn deep-walk
  [f data]
  (map (fn [s] (if (seq? s) 
                 (deep-walk f s) 
                 (f s))) 
        data))

And this slight variation for vectors:

(defn vec-deep-walk
  [f data]
  (vec (map (fn [s] (if (vector? s) 
                      (vec-deep-walk f s) 
                      (f s))) 
            data)))

Just a quick test with the following:

(vec-deep-walk (partial + 1) [1 [2 3] 4 [5 [6 7]]])

Gives the following output:

[2 [3 4] 5 [6 [7 8]]]

The walk functions take two parameters, the first is a function that takes a single parameter. This will be called for each non-seq/vector element in your data, which is passed as the second parameter. The results will be returned in a nested structure that is identical to the input structure.

1
  • Leonid's for solution will work if the nesting is consistent and one level deep. It is admittedly a simpler solution in that case. The recursive solution will deal with any level of complexity in the nested structure in a more general solution.
    – Mike
    Nov 17, 2015 at 2:16

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.