# Comp 110 Union

## Union

Union refers to the elements that are present in either set.

A ∪ B

## Example

1. Write an expression that represents all Main Characters AND all Gryffindor students.
2. Write an expression that represents all Slytherin AND Gryffindor students who are not also Main Characters.

1. MC ∪ SG
2. (SS ∪ SG) - MC
1. Check out the page of Difference!

## Implementing a 'union' Function

GOAL: write a function that cons all elements of list A onto a new list ending with B while preventing duplicates

STEP 1: combine lists A and B

1. If A is null, then return B
2. Else, cons the first element of A onto the union function applied recursively on the rest of A and all of B

STEP 2: remove duplicates

1. Add an else-if condition after the then-block
2. The condition of the else-if should test to see if set B includes the first element of A
3. If it does, recur without cons'ing
``````let union = <T>(a: List<T>, b: List<T>): List<T> => {
if (a === null) {
return b;
} else if (includes(b, first(a))) {
return union(rest(a), b);
} else {
return cons(first(a), union(rest(a), b));
}
};``````

How do we use this function?

Assume we have two lists (SG and SS for Gryffindor and Slytherin Students) that we want to unionize into one singular list called sgStudents

``````let sgStudents: List<Student> = union(gryffindorStudents, slytherinStudents);
print (sgStudnets);``````