Docsity

Bags in Software Engineering: Understanding Unordered Collections with Duplicates, Slides of Software Engineering

Partial preview of the text

Download Bags in Software Engineering: Understanding Unordered Collections with Duplicates and more Slides Software Engineering in PDF only on Docsity!

LECTURE 14: BAGS (MULTISETS)

Software Engineering

1 Bags

  • We have seen that sets are unordered collections of items, which do not contain duplicates.
  • A sequence is an ordered collection of items, that may contain duplicates.
  • A bag is an unordered collection of items that may contain duplicates.
  • Bags are sometimes called multisets.

Ordered? Duplicates? Set N N Sequence Y Y Bag N Y

2 Bag Membership and Sub-bags

  • The ‘equivalent’ of the set membership predicate ∈ is ‘in’. (This is sometime written ‘ ’.)
  • Definition: If

B : bag T x : T then the predicate x in B is true iff x appears in B at least once.

  • The ‘equivalent’ of the subset predicate ⊂ is v.
  • Definition: If

B 1 , B 2 : bag T then the predicate B 1 v B 2 is true iff each element that occurs in B 1 occurs in B 1 no more often than it occurs in B 2.

  • Summary:

a in b a is a member of bag b b v c b is a sub-bag of c

  • EXAMPLES.

jan in [[mar, mar, feb]] ¬(apr in [[mar, mar, feb]]) [[jan, feb]] v [[jan, mar, feb, apr]] [[jan, feb]] v [[jan, feb]]

  • Some theorems about bag membership and sub-bags.

[[ ]] v B B v C ∧ C v B ⇔ B = C B v C ∧ C v D ⇒ B v D

4 Scaling Bags

  • Another common operation we want to do is scale bags; that is, we want to ‘multiply’ their contents. We do this using the bag scaling operator: ⊗.
  • EXAMPLE. Let

storms == [[jan, jan, feb]] then 2 ⊗ storms = [[jan, jan, jan, jan, feb, feb]].

  • Definition: If

B : bag T n : IN then n ⊗ B is a bag which contains the same elements as B, except that every element that occurs m times in B occurs n ∗ m times in n ⊗ B.

  • Some theorems about scaling...

n ⊗ [[ ]] = [[ ]] 0 ⊗ B = [[ ]] 1 ⊗ B = B (n ∗ m) ⊗ B = n ⊗ (m ⊗ B)

6 Making Bags out of Sequences

  • One last thing we often want to do is to make a bag out of a sequence, by counting up all number of times in a sequence. We do this using items. EXAMPLE. items〈a, b, a, b, c〉 = [[a, a, b, b, c]] items〈a, c, d, a, a〉 = [[a, a, a, c, d]]
  • Definition: If

σ : seq T then items(σ) is a bag over T such that a value x occurs in items(σ) exactly as many times as it appears in σ.

7 A Model for Bags

  • In the previous lecture, we saw that sequences are defined in terms of functions. 〈a, b, c〉 = { 1 7 → a, 2 7 → b, 3 7 → c}. Bags are defined in a similar way: bag T == T → 7 IN 1
  • So the bag

[[jan, feb, jan]] is really the function {jan 7 → 2 , feb 7 → 1 }.

  • So we can use all the function manipuating operations to manipulate bags.
  • In particular:

dom[[a 1 ,... , an]] = {a 1 ,... , an} and so dom[[jan, jan, feb]] = {jan, feb}.

  • Taking the range of a bag is not generally as useful.