Skip to content

Commit

Permalink
add union
Browse files Browse the repository at this point in the history
  • Loading branch information
brekk committed Apr 3, 2024
1 parent a734078 commit 4f699b7
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
26 changes: 24 additions & 2 deletions prelude/__internal__/List.mad
Original file line number Diff line number Diff line change
Expand Up @@ -1084,14 +1084,36 @@ export cut = (a, xs) => {
Nothing
}
}

/**
* Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list.
* @example
* difference([1,2,3,4], [7,6,5,4,3]) // [1,2]
* difference([7,6,5,4,3], [1,2,3,4]) // [7,6,5]
*/
difference :: Eq a => List a -> List a -> List a
export difference = (z, a) => reduce((stack, c) => includes(c, a) ? stack : [...stack, c], [], z)


/**
* Finds the set (i.e. no duplicates) of all elements contained in the first or second list, but not both.
* @example
* symmetricDifference([1,2,3,4], [7,6,5,4,3]) // [1,2,7,6,5]
* symmetricDifference([7,6,5,4,3], [1,2,3,4]) // [7,6,5,1,2]
*/
symmetricDifference :: Eq a => List a -> List a -> List a
export symmetricDifference = (z, a) => reduce(
(stack, c) => includes(c, a) && includes(c, z) ? stack : [...stack, c],
[],
concat(z, a),
)

/**
* Combines two lists into a set (i.e. no duplicates) composed of the elements of each list
* @example
* union([1, 2, 3], [2, 3, 4]) // [1, 2, 3, 4]
*/
union :: Eq a => List a -> List a -> List a
export union = (a, z) => reduce(
(stack, c) => includes(c, stack) ? stack : [...stack, c],
[],
concat(a, z),
)
3 changes: 3 additions & 0 deletions prelude/__internal__/List.spec.mad
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import {
take,
takeLast,
takeWhile,
union,
uniqueBy,
} from "./List"

Expand Down Expand Up @@ -302,3 +303,5 @@ test(
"symmetricDifference",
() => assertEquals(symmetricDifference([7, 6, 5, 4, 3], [1, 2, 3, 4]), [7, 6, 5, 1, 2]),
)

test("union", () => assertEquals(union(range(1, 11), range(11, 21)), range(1, 21)))

0 comments on commit 4f699b7

Please sign in to comment.