This page describes an operation in the collection pipeline pattern. For more context read:
- Collection Pipeline Article: An article explaining the collection pipeline pattern
- Operation Catalog: The list of selected operations that I have these pages for.
intersection
Retains elements that are also in the supplied collection
The notion of a set intersection isn't one that's fundamental to collection pipelines — it naturally fits in better with nested operator expressons — but it is sometimes useful.
Rather than use an explicit intersection function, it's often more straightforward to use filter
[1,1,2,2,3,4].select{|i| [1,3].include? i} # => [1, 1, 3]
(filter #{1 3} [1 1 2 2 3 4]) ;; => (1 1 3)
When operating on a list like this, using a filter naturally results in a result that includes duplicates from the source collection, as well as preserving ordering. If you need to remove duplicates, as you would expect with a set operation, you need to follow the intersection with distinct.
Ruby provides an operator for set intersection.
ruby…[1,1,2,2,3,4] & [1,3] # => [1, 3]
As it's expected to be used in the context of set manipulation, the intersection operator does remove duplicates. Like any infix operator, however, it's awkward to use in a pipeline.
Clojure supplies an intersection function defined on its set data structure. To use it in a pipeline with a sequence, you need to convert the sequence to a set first, and convert back to a sequence when you're done if you need that as your result.
clojure…(->> [1 1 2 2 3 4] (set) (intersection #{1 3}) (into [])) ;; => [1 3]