Today’s Erlang Thursday is on ordsets:union/2.
ordsets:union/2
takes two ordered sets and returns an merged ordered set of the arguments.
SetA = ordsets:from_list([1, 1, 2, 3, 5]). % [1,2,3,5] SetB = ordsets:new(). % [] SetC = ordsets:from_list([3, 1, 4, 1, 5, 9]). % [1,3,4,5,9] SetD = ordsets:from_list([a, b, c, d, e]). % [a,b,c,d,e] UnionAB = ordsets:union(SetA, SetB). % [1,2,3,5] UnionAC = ordsets:union(SetA, SetC). % [1,2,3,4,5,9]
And because a string in Erlang is just a list of characters, we can also create ordered sets from strings, and then get a union of the unique characters that are in two strings.
ordsets:from_list("Kermit"). % "Keimrt" ordsets:from_list([75, 101, 114, 109, 105, 116]). % "Keimrt" ordsets:from_list("Mississippi"). % "Mips" ordsets:union(ordsets:from_list("Kermit"), ordsets:from_list("Mississippi")). % "KMeimprst"
The ordsets
modules also contains ordsets:union/1, which takes a list of ordered sets and returns the union of all the ordered sets in the list.
UnionAC = ordsets:union([SetA, SetC]). % [1,2,3,4,5,9] UnionABC = ordsets:union([SetB, SetC, SetA]). % [1,2,3,4,5,9] UnionABCD = ordsets:union([SetB, SetC, SetA, SetD]). % [1,2,3,4,5,9,a,b,c,d,e] UnionCD = ordsets:union([SetC, SetD]). % [1,3,4,5,9,a,b,c,d,e]
WARNING: While the representation for an ordered set is just a list, if you pass a list to ordsets:union/2
you will not get what you expect, as it expects the items in each “ordered set” to actually be ordered and a set.
ordsets:union([1, 2, 3], [a, b, c]). % [1,2,3,a,b,c] ordsets:union([1, 1, 2, 3, 1, 2], [a, b, c]). % [1,1,2,3,1,2,a,b,c] ordsets:union([1, 1, 2, 3, 1, 2], [1, a, b, c]). % [1,1,2,3,1,2,a,b,c] ordsets:union([1, 1, 2, 3, 1, 2], [1, a, b, c, 1]). % [1,1,2,3,1,2,a,b,c,1]
–Proctor
Pingback: Erlang Thursday - ordsets:intersection/2 | Proctor It