Take-while and take-nth in clojure

187 views Asked by At

I'm trying to get n messages from a queue (using langohr). I have a working version but I would like to know if there is a better clojurist way of doing this:

(def not-nil? (complement nil?))

(defn get_message [queue] 
   (let [[_ payload] (lb/get ch queue)]
       (if (not-nil? payload)
         (String. payload "UTF-8"))))


(take 4 (take-while not-nil? (repeatedly (partial get_message "my_queue"))))

So I fetch up to N messages as long as there are messages in the queue.

Is there a better clojurist way to do this?

1

There are 1 answers

2
noisesmith On BEST ANSWER

not-nil? is the same as the built in function some? in clojure 1.6

The idiom is to use - in preference to _ in Clojure binding names.

(partial get_message "my_queue") is better as #(get-message "my_queue") since you clearly have no intention of adding args

(if (some? payload) (String. payload "UTF-8"))

could be expressed as

(some-> payload (String. "UTF-8")),

though you may want to reserve some-> for longer chaining, it's still more concise in this case.

So, putting this all together:

(defn get-message [queue]
  (let [[_ payload] (lb/get ch queue)]
    (some-> payload (String. "UTF-8"))))

(take 4 (take-while some? (repeatedly #(get-message "my_queue"))))