4

I'm writing a simple photo library app in Clojure. I have a library map that has the :photos key which is a vector of photo maps. Then, I have a function that adds a photo to a library---it takes the library object and the photo to be added as arguments.

(defn add-to-library [library photo]
  ...
)

It returns a library map with the photo added.

Now, I want to "map" this function over a list of photos. I need to be able to pass the library object through from one iteration to the next.

What is the idiomatic way of doing this in Clojure?

1 Answer 1

7

Try:

(reduce add-to-library library list-of-photos).

The reduce function is wonderful, and is a general tool that is surprisingly applicable in a lot of specific situations. Many of those situations are ones like yours, where you have a "collection of things", a "function that adds a thing to that collection", and a "list of things to add". Maybe this isn't starting material if first learning about reduce, but I found it very interesting: http://clojure.com/blog/2012/05/08/reducers-a-library-and-model-for-collection-processing.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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