Search code examples
listclojureintersection

How do I compute a list intersection in Clojure?


I need a function that takes two lists, e.g. (1 2 3 4) and (2 3 4 5), and returns their intersection, i.e. (2 3 4). I wrote up a function that works but it's 8 lines long and very "un-Clojurelike," owing to my newness to the sport. I know there's something elegant out there, hell, maybe even a Clojure keyword that solves the whole problem. The comparison needs to only be at the top level, not recursing through the entire list structures. Thank you in advance.


Solution

  • There is built-in library for set operation if you don't mind the sequence of result set.

    (require '[clojure.set :as set])
    (set/intersection (set '(1 2 3 4) ) (set '( 3 4 5)))   ; ==> returns #{4 3}