2
\$\begingroup\$

I currently use a data structure like this:

(def sample-board 
  [[{:mine true} {:warn 2   } {:warn 1} {          }]
   [{:warn 2   } {:mine true} {:warn 1} {          }]
   [{:warn 1   } {:warn 1   } {:warn 2} {:warn 1   }]
   [{          } {          } {:warn 1} {:mine true}]])

Now I want to create a copy of the first structure and each element should be supplemented with :explored true.

My approach so far looks like this:

(def sample-board-solved
  (map (partial map 
                (partial conj {:explored true})) 
       sample-board))

I don't find the approach very appealing though. I thought about using for instead or maybe recur in combination with update-in but I did not bring it to work yet.

I'd be glad on suggestions how to improve the code.

\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

You could maybe make your solution a bit neater by using a lambda in place of one of your partials. assoc might be a little clearer in purpose than a conj as well:

(def sample-board-solved
  (map (partial map #(assoc % :explored true))
       sample-board))

Using map like this will return things in sequences rather than vectors like the input data. If it's particularly important that you get vectors out you can always use mapv

\$\endgroup\$
1
  • \$\begingroup\$ +1. Also, if this pattern happens a lot, OP could define a 2-depth or "board-cell-level" map: (defn mapmap [f coll] (map (partial map f) coll)) \$\endgroup\$
    – BenC
    Commented Jan 15, 2016 at 23:55

Your Answer

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

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