Object Commando languages, development and design

22Feb/100

Clojure Apply

I ran into the following situation a few times, I had a list of items, and I was attempting to call a function that accepted individual items. As an example, I had a list of contact information, where the first element is the contact name, the second, contact info, the third a contact name and so on. This is exactly how the sorted-map function works in Clojure, only it expects the items individually, not the list. The doc for sorted-map is below:

clojure.core/sorted-map
([& keyvals])
keyval => key val
Returns a new sorted map with supplied mappings.

An example of how to call it is something like:

user> (sorted-map 1 2 3 4)
{1 2, 3 4}

What I had instead was something like [1 2 3 4]. An easy way to convert the list to individual arguments is the apply function:

clojure.core/apply
([f args* argseq])
Applies fn f to the argument list formed by prepending args to argseq.

Swapping out the direct sorted-map call for an apply call looks like:

user> (apply sorted-map '(1 2 3 4))
{1 2, 3 4}

Note it returns the same result as calling the function directly. Using apply saved me from writing code to iterate over each item and manually add them to the map.

Filed under: Languages Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

No trackbacks yet.