liveBook · Manning

Setdiff

As explained in Julia as a Second Language

setdiff is a Julia function that returns the elements present in one collection but absent from one or more other collections.

Use setdiff to keep elements present in one collection after removing anything also found in another. The argument order matters: setdiff(A, B) differs from setdiff(B, A). This is useful when excluding unwanted records, such as vacation photos containing Joe from Eve’s photo set. section 13.3

In Julia, setdiff fits naturally with other set operations:

  • setdiff(eve, joe) keeps Eve’s captions that do not also appear in Joe’s set, returning “Eve in Wales” and “Eve in Spain”. section 13.3
  • setdiff(A, B) returns 4 and 2 for A = Set([1, 2, 4, 6]) and B = Set([1, 3, 5, 6]); reversing the arguments returns 5 and 3. section 13.3
  • Use setdiff alongside intersect and union when combining criteria, such as selecting products or screws that match some categories while excluding others. section 13.4
julia> setdiff(eve, joe)
Set{String} with 2 elements:
 "Eve in Wales"
 "Eve in Spain"

Inspect a runnable photo-caption example showing setdiff(eve, joe) and its two-element result. section 13.3

julia> setdiff(A, B)
Set{Int64} with 2 elements:
 4
 2

julia> setdiff(B, A)
Set{Int64} with 2 elements:
 5
 3

Compare setdiff(A, B) with setdiff(B, A) to see concretely why set difference is directional. section 13.3

How Julia as a Second Language covers it

How deep it goes
Explains directional behavior with photo and numeric examples, but defers implementation internals.
Examples
Uses vacation captions, numeric sets, product categories, and screw-selection criteria.
What it assumes
Assumes basic collections and sets while introducing set operations through concrete examples.
What you can do after
Apply it to remove members shared with other sets and interpret the effect of reversing operands.
How it connects
Connects setdiff with sets, union, intersect, filter, arrays, and relational algebra.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Julia as a Second Language. The section links point to the parts of the book it draws on.