What is the difference between merging a List and merging a Set with ':~:'?

← Collections and Data Structures · Ref: Q1409

A List APPENDS and a Set takes the UNION. ':~:' never overwrites a set value and fills whatever is unset or missing - but a List or a Set has no element to fill (no key, no position that can be unset), so merging one simply combines.

LIST

The source's items are added at the end, in order, duplicates and all. An unset item merged in on its own is dropped.

  names <- ["ann", "bob"]
  names :~: ["cat", "ann"]
  stdout.println($names)

SET

The source's items are added unless already present, so a shared item appears once.

INSIDE A DICT

A List held in a Dict is merged into, so the Lists under a shared key append (see Q1408).

See Q1405 for the rule on single values. See Q1081 for merging Lists. See Q1365 for Sets.

Example

defines module qa.collections.mergelistvsset

  defines program

    MergeListVsSetDemo()
      stdout <- Stdout()

      //A List appends, in order, duplicates and all
      names <- ["ann", "bob"]
      names :~: ["cat", "ann"]
      stdout.println(`list: ${names}`)

      //A Set takes the union
      unique <- Set() of String
      unique += "ann"
      unique += "bob"

      others <- Set() of String
      others += "bob"
      others += "cat"

      unique :~: others
      stdout.println(`set size: ${length unique}`)
      stdout.println(`set holds cat: ${unique contains "cat"}`)
Other ways to ask this
  • Does ':~:' on a List remove duplicates?
  • Does merging two Sets keep both copies of a shared item?
  • In what order does a List merge add items?
  • Why does merging Lists append when merging Dicts does not overwrite?

Coming from another language?

Java: list.addAll(other) appends; set.addAll(other) is the union. Python: list.extend and set.update (|=). EK9: one operator for both - ':~:' appends a List and unions a Set.

Keywords: merge, append, list merge order, union, duplicates, :~:, list