4
votes

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

1 Answers

7
votes

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