This is basically a problem of parallel iteration. I've devised 2 solutions, one is recursive (alas, not tail-recursive) and the other appears to be a more idiomatic Clojure solution. Can someone suggest a more efficient or cleaner solution?
Here's the "literal" solution: (defn matching-elements [coll1 coll2] (if (or (empty? coll1) (empty? coll2)) () (let [e1 (first coll1) e2 (first coll2)] (if (= e1 e2) (cons e1 (matching-elements (rest coll1) (rest coll2))) (matching-elements (rest coll1) (rest coll2)))))) In this implementation, we first check the base case, where one of the sequences is empty. If one of the sequences is empty, we return an empty list. Otherwise, we check to see if the first elements in each list are equal. If so, we return the list resulting from the addition of the matching element to the result of the recursive call to the method on the remaining elements in each list. Otherwise, we simply return the result of the recursive call to the method on the remaining elements in each list. I believe that the cons prevents the use of recur to make this tail recursive. After a little digging and reading through a thread on this group about parallel iteration, I devised the following alternative solution, which makes use of lazy sequences: (defn matching-elements2 [coll1 coll2] (map first (filter #(let [[e1 e2] %] (= e1 e2)) (partition 2 (interleave coll1 coll2))))) Can anyone suggest an improved implementation of either implementation? Thanks! --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~----------~----~----~----~------~----~------~--~---