Class: Hamster::Set

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/hamster/set.rb

Overview

Hamster::Set is a collection of unordered values with no duplicates. Testing whether an object is present in the Set is fast. Set is also Enumerable, so you can iterate over the members of the set with #each, transform them with #map, filter them with #select, and so on. Some of the Enumerable methods are overridden to return Hamster collections.

Like the Set class in Ruby's standard library, which we will call RubySet, Hamster::Set defines equivalency of objects using #hash and #eql?. No two objects with the same #hash code, and which are also #eql?, can coexist in the same Set. If one is already in the Set, attempts to add another one will have no effect.

Sets have no natural ordering and cannot be compared using #<=>. However, they define #<, #>, #<=, and #>= as shorthand for #proper_subset?, #proper_superset?, #subset?, and #superset? (respectively).

The basic set-theoretic operations #union, #intersection, #difference, and #exclusion work with any Enumerable object. They may be more efficient when used with another Hamster::Set, or a RubySet.

A Set can be created in any of the following ways:

Hamster.set('Tom', 'Dick', 'Harry')
Hamster::Set.new([1, 2, 3]) # any Enumerable can be used to initialize
Hamster::Set['A', 'B', 'C', 'D']

The latter 2 forms of initialization can be used with your own, custom subclasses of Hamster::Set.

Unlike RubySet, all methods which you might expect to "modify" a Hamster::Set actually return a new set and leave the existing one unchanged.

Examples:

require 'hamster/set'
set1 = Hamster.set(1, 2)  # => Hamster::Set[1, 2]
set2 = Hamster::Set[1, 2] # => Hamster::Set[1, 2]
set1 == set2              # => true
set3 = set1.add("foo")    # => Hamster::Set[1, 2, "foo"]
set3 - set2               # => Hamster::Set["foo"]
set3.subset?(set1)        # => false
set1.subset?(set3)        # => true

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Enumerable

#<=>, #compact, #each_index, #grep, #group_by, #inspect, #join, #partition, #product, #reject, #sum

Methods included from Enumerable

#to_list

Constructor Details

#initialize(items = []) ⇒ Set

Returns a new instance of Set


86
87
88
89
# File 'lib/hamster/set.rb', line 86

def initialize(items=[])
  @trie = Trie.new(0)
  items.each { |item| @trie.put!(item, nil) }
end

Class Method Details

.[](*items) ⇒ Set

Create a new Set populated with the given items.

Returns:


64
65
66
# File 'lib/hamster/set.rb', line 64

def [](*items)
  new(items)
end

.emptySet

Return an empty Set. If used on a subclass, returns an empty instance of that class.

Returns:


72
73
74
# File 'lib/hamster/set.rb', line 72

def empty
  @empty ||= self.new
end

Instance Method Details

#add(item) ⇒ Set Also known as: <<

Return a new Set with item added. If item is already in the set, return self.

Examples:

Hamster::Set[1, 2, 3].add(4) # => Hamster::Set[1, 2, 4, 3]
Hamster::Set[1, 2, 3].add(2) # => Hamster::Set[1, 2, 3]

Parameters:

  • item (Object)

    The object to add

Returns:


113
114
115
# File 'lib/hamster/set.rb', line 113

def add(item)
  include?(item) ? self : self.class.alloc(@trie.put(item, nil))
end

#add?(item) ⇒ Set, false

If item is not a member of this Set, return a new Set with item added. Otherwise, return false.

Examples:

Hamster::Set[1, 2, 3].add?(4) # => Hamster::Set[1, 2, 4, 3]
Hamster::Set[1, 2, 3].add?(2) # => false

Parameters:

  • item (Object)

    The object to add

Returns:


127
128
129
# File 'lib/hamster/set.rb', line 127

def add?(item)
  !include?(item) && add(item)
end

#clearHash

Return an empty Set instance, of the same class as this one. Useful if you have multiple subclasses of Set and want to treat them polymorphically.

Returns:


507
508
509
# File 'lib/hamster/set.rb', line 507

def clear
  self.class.empty
end

#delete(item) ⇒ Set

Return a new Set with item removed. If item is not a member of the set, return self.

Examples:

Hamster::Set[1, 2, 3].delete(1)  # => Hamster::Set[2, 3]
Hamster::Set[1, 2, 3].delete(99) # => Hamster::Set[1, 2, 3]

Parameters:

  • item (Object)

    The object to remove

Returns:


140
141
142
143
# File 'lib/hamster/set.rb', line 140

def delete(item)
  trie = @trie.delete(item)
  new_trie(trie)
end

#delete?(item) ⇒ Set, false

If item is a member of this Set, return a new Set with item removed. Otherwise, return false.

Examples:

Hamster::Set[1, 2, 3].delete?(1)  # => Hamster::Set[2, 3]
Hamster::Set[1, 2, 3].delete?(99) # => false

Parameters:

  • item (Object)

    The object to remove

Returns:


154
155
156
# File 'lib/hamster/set.rb', line 154

def delete?(item)
  include?(item) && delete(item)
end

#difference(other) ⇒ Set Also known as: subtract, -

Return a new Set with all the items in other removed. other can be any Enumerable object.

Examples:

Hamster::Set[1, 2] - Hamster::Set[2, 3] # => Hamster::Set[1]

Parameters:

  • other (Enumerable)

    The collection to subtract from this set

Returns:


349
350
351
352
353
354
355
356
# File 'lib/hamster/set.rb', line 349

def difference(other)
  trie = if (@trie.size <= other.size) && (other.is_a?(Hamster::Set) || (defined?(::Set) && other.is_a?(::Set)))
    @trie.select { |key, _| !other.include?(key) }
  else
    @trie.bulk_delete(other)
  end
  new_trie(trie)
end

#disjoint?(other) ⇒ Boolean

Return true if this Set and other do not share any items.

Examples:

Hamster::Set[1, 2].disjoint?(Hamster::Set[8, 9]) # => true

Parameters:

Returns:

  • (Boolean)

451
452
453
454
455
456
457
458
459
460
461
462
# File 'lib/hamster/set.rb', line 451

def disjoint?(other)
  if other.size <= size
    other.each { |item| return false if include?(item) }
  else
    # See comment on #subset?
    if other.size >= 150 && @trie.size >= 190 && !(other.is_a?(Hamster::Set) || other.is_a?(::Set))
      other = ::Set.new(other)
    end
    each { |item| return false if other.include?(item) }
  end
  true
end

#eachself

Call the block once for each item in this Set. No specific iteration order is guaranteed (but the order will be stable for any particular Set.)

Examples:

Hamster::Set["Dog", "Elephant", "Lion"].each { |e| puts e }
Elephant
Dog
Lion
# => Hamster::Set["Dog", "Elephant", "Lion"]

Returns:

  • (self)

169
170
171
172
173
# File 'lib/hamster/set.rb', line 169

def each
  return to_enum if not block_given?
  @trie.each { |key, _| yield(key) }
  self
end

#empty?Boolean

Return true if this Set contains no items.

Returns:

  • (Boolean)

93
94
95
# File 'lib/hamster/set.rb', line 93

def empty?
  @trie.empty?
end

#eql?(other) ⇒ Boolean Also known as: ==

Return true if other has the same type and contents as this Set.

Parameters:

  • other (Object)

    The object to compare with

Returns:

  • (Boolean)

515
516
517
518
519
520
521
522
523
524
# File 'lib/hamster/set.rb', line 515

def eql?(other)
  return true if other.equal?(self)
  return false if not instance_of?(other.class)
  other_trie = other.instance_variable_get(:@trie)
  return false if @trie.size != other_trie.size
  @trie.each do |key, _|
    return false if !other_trie.key?(key)
  end
  true
end

#exclusion(other) ⇒ Set Also known as: ^

Return a new Set which contains all the items which are members of this Set or of other, but not both. other can be any Enumerable object.

Examples:

Hamster::Set[1, 2] ^ Hamster::Set[2, 3] # => Hamster::Set[1, 3]

Parameters:

  • other (Enumerable)

    The collection to take the exclusive disjunction of

Returns:


368
369
370
# File 'lib/hamster/set.rb', line 368

def exclusion(other)
  ((self | other) - (self & other))
end

#firstObject

Return a member of this Set. The member chosen will be the first one which would be yielded by #each. If the set is empty, return nil.

Examples:

Hamster::Set["A", "B", "C"].first # => "C"

Returns:

  • (Object)

244
245
246
# File 'lib/hamster/set.rb', line 244

def first
  (entry = @trie.at(0)) && entry[0]
end

#flattenSet

Recursively insert the contents of any nested Sets into this Set, and remove them.

Examples:

Hamster::Set[Hamster::Set[1, 2], Hamster::Set[3, 4]].flatten
# => Hamster::Set[1, 2, 3, 4]

Returns:


483
484
485
486
487
488
# File 'lib/hamster/set.rb', line 483

def flatten
  reduce(self.class.empty) do |set, item|
    next set.union(item.flatten) if item.is_a?(Set)
    set.add(item)
  end
end

#hashInteger

See Object#hash.

Returns:

  • (Integer)

529
530
531
# File 'lib/hamster/set.rb', line 529

def hash
  reduce(0) { |hash, item| (hash << 5) - hash + item.hash }
end

#include?(object) ⇒ Boolean Also known as: member?

Return true if the given item is present in this Set. More precisely, return true if an object with the same #hash code, and which is also #eql? to the given object is present.

Examples:

Hamster::Set["A", "B", "C"].include?("B") # => true
Hamster::Set["A", "B", "C"].include?("Z") # => false

Parameters:

  • object (Object)

    The object to check for

Returns:

  • (Boolean)

232
233
234
# File 'lib/hamster/set.rb', line 232

def include?(object)
  @trie.key?(object)
end

#intersect?(other) ⇒ Boolean

Return true if this Set and other have at least one item in common.

Examples:

Hamster::Set[1, 2].intersect?(Hamster::Set[2, 3]) # => true

Parameters:

Returns:

  • (Boolean)

471
472
473
# File 'lib/hamster/set.rb', line 471

def intersect?(other)
  !disjoint?(other)
end

#intersection(other) ⇒ Set Also known as: &

Return a new Set which contains all the items which are members of both this Set and other. other can be any Enumerable object.

Examples:

Hamster::Set[1, 2] & Hamster::Set[2, 3] # => Hamster::Set[2]

Parameters:

  • other (Enumerable)

    The collection to intersect with

Returns:


326
327
328
329
330
331
332
333
334
335
336
337
338
# File 'lib/hamster/set.rb', line 326

def intersection(other)
  if other.size < @trie.size
    if other.is_a?(Hamster::Set)
      trie = other.instance_variable_get(:@trie).select { |key, _| include?(key) }
    else
      trie = Trie.new(0)
      other.each { |obj| trie.put!(obj, nil) if include?(obj) }
    end
  else
    trie = @trie.select { |key, _| other.include?(key) }
  end
  new_trie(trie)
end

#mapSet Also known as: collect

Call the block once for each item in this Set. All the values returned from the block will be gathered into a new Set.

Examples:

Hamster::Set["Cat", "Elephant", "Dog", "Lion"].map { |e| e.size }
# => Hamster::Set[8, 4, 3]

Returns:


215
216
217
218
219
# File 'lib/hamster/set.rb', line 215

def map
  return enum_for(:map) if not block_given?
  return self if empty?
  self.class.new(super)
end

#proper_subset?(other) ⇒ Boolean Also known as: <

Returns true if other contains all the items in this Set, plus at least one item which is not in this set.

Examples:

Hamster::Set[2, 3].proper_subset?(Hamster::Set[1, 2, 3])    # => true
Hamster::Set[1, 2, 3].proper_subset?(Hamster::Set[1, 2, 3]) # => false

Parameters:

Returns:

  • (Boolean)

420
421
422
423
424
425
426
427
# File 'lib/hamster/set.rb', line 420

def proper_subset?(other)
  return false if other.size <= size
  # See comments above
  if other.size >= 150 && @trie.size >= 190 && !(other.is_a?(Hamster::Set) || other.is_a?(::Set))
    other = ::Set.new(other)
  end
  all? { |item| other.include?(item) }
end

#proper_superset?(other) ⇒ Boolean Also known as: >

Returns true if this Set contains all the items in other, plus at least one item which is not in other.

Examples:

Hamster::Set[1, 2, 3].proper_superset?(Hamster::Set[2, 3])    # => true
Hamster::Set[1, 2, 3].proper_superset?(Hamster::Set[1, 2, 3]) # => false

Parameters:

Returns:

  • (Boolean)

439
440
441
# File 'lib/hamster/set.rb', line 439

def proper_superset?(other)
  other.proper_subset?(self)
end

#reverse_eachself

Call the block once for each item in this Set. Iteration order will be the opposite of #each.

Examples:

Hamster::Set["Dog", "Elephant", "Lion"].reverse_each { |e| puts e }
Lion
Dog
Elephant
# => Hamster::Set["Dog", "Elephant", "Lion"]

Returns:

  • (self)

186
187
188
189
190
# File 'lib/hamster/set.rb', line 186

def reverse_each
  return enum_for(:reverse_each) if not block_given?
  @trie.reverse_each { |key, _| yield(key) }
  self
end

#sampleObject

Return a randomly chosen item from this Set. If the set is empty, return nil.

Examples:

Hamster::Set[1, 2, 3, 4, 5].sample # => 3

Returns:

  • (Object)

499
500
501
# File 'lib/hamster/set.rb', line 499

def sample
  empty? ? nil : @trie.at(rand(size))[0]
end

#selectSet Also known as: find_all, keep_if

Return a new Set with all the items for which the block returns true.

Examples:

Hamster::Set["Elephant", "Dog", "Lion"].select { |e| e.size >= 4 }
# => Hamster::Set["Elephant", "Lion"]

Returns:


199
200
201
202
203
# File 'lib/hamster/set.rb', line 199

def select
  return enum_for(:select) unless block_given?
  trie = @trie.select { |key, _| yield(key) }
  new_trie(trie)
end

#sizeInteger Also known as: length

Return the number of items in this Set.

Returns:

  • (Integer)

99
100
101
# File 'lib/hamster/set.rb', line 99

def size
  @trie.size
end

#sort {|a, b| ... } ⇒ SortedSet

Return a Hamster::SortedSet which contains the same items as this Set, ordered by the given comparator block. The comparator block should take 2 parameters and return 0, 1, or -1 depending on whether the first parameter is equal, greater than, or less than the second.

Examples:

Hamster::Set["Elephant", "Dog", "Lion"].sort
# => Hamster::SortedSet["Dog", "Elephant", "Lion"]
Hamster::Set["Elephant", "Dog", "Lion"].sort { |a,b| a.size <=> b.size }
# => Hamster::SortedSet["Dog", "Lion", "Elephant"]

Yields:

  • (a, b)

    A pair of items to be compared

Yield Returns:

  • (Integer)

Returns:


262
263
264
# File 'lib/hamster/set.rb', line 262

def sort(&comparator)
  SortedSet.new(self.to_a, &comparator)
end

#sort_by {|item| ... } ⇒ SortedSet

Return a Hamster::SortedSet which contains the same items as this Set, ordered by mapping each item through the provided block to obtain sort keys, and then sorting the keys.

It is recommended that the provided block should be a pure function, since it may be called again later when certain operations are performed on the returned Hamster::SortedSet.

Examples:

Hamster::Set["Elephant", "Dog", "Lion"].sort_by { |e| e.size }
# => Hamster::SortedSet["Dog", "Lion", "Elephant"]

Yields:

  • (item)

    The item to obtain a sort key for

Yield Returns:

  • (Object)

Returns:


281
282
283
# File 'lib/hamster/set.rb', line 281

def sort_by(&mapper)
  SortedSet.new(self.to_a, &mapper)
end

#subset?(other) ⇒ Boolean Also known as: <=

Return true if all items in this Set are also in other.

Examples:

Hamster::Set[2, 3].subset?(Hamster::Set[1, 2, 3]) # => true

Parameters:

Returns:

  • (Boolean)

380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
# File 'lib/hamster/set.rb', line 380

def subset?(other)
  return false if other.size < size

  # This method has the potential to be very slow if 'other' is a large Array, so to avoid that,
  #   we convert those Arrays to Sets before checking presence of items
  # Time to convert Array -> Set is linear in array.size
  # Time to check for presence of all items in an Array is proportional to set.size * array.size
  # Note that both sides of that equation have array.size -- hence those terms cancel out,
  #   and the break-even point is solely dependent on the size of this collection
  # After doing some benchmarking to estimate the constants, it appears break-even is at ~190 items
  # We also check other.size, to avoid the more expensive #is_a? checks in cases where it doesn't matter
  #
  if other.size >= 150 && @trie.size >= 190 && !(other.is_a?(Hamster::Set) || other.is_a?(::Set))
    other = ::Set.new(other)
  end
  all? { |item| other.include?(item) }
end

#superset?(other) ⇒ Boolean Also known as: >=

Return true if all items in other are also in this Set.

Examples:

Hamster::Set[1, 2, 3].superset?(Hamster::Set[2, 3]) # => true

Parameters:

Returns:

  • (Boolean)

406
407
408
# File 'lib/hamster/set.rb', line 406

def superset?(other)
  other.subset?(self)
end

#to_ruby::Set

Deeply convert to Ruby Set.

Returns:

  • (::Set)

546
547
548
# File 'lib/hamster/set.rb', line 546

def to_ruby
  Hamster.to_ruby(self)
end

#to_setself

Return self.

Returns:

  • (self)

539
540
541
# File 'lib/hamster/set.rb', line 539

def to_set
  self
end

#union(other) ⇒ Set Also known as: |, +, merge

Return a new Set which contains all the members of both this Set and other. other can be any Enumerable object.

Examples:

Hamster::Set[1, 2] | Hamster::Set[2, 3] # => Hamster::Set[1, 2, 3]

Parameters:

  • other (Enumerable)

    The collection to merge with

Returns:


293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/hamster/set.rb', line 293

def union(other)
  if other.is_a?(Hamster::Set)
    if other.size > size
      small_set_pairs = @trie
      large_set_trie = other.instance_variable_get(:@trie)
    else
      small_set_pairs = other.instance_variable_get(:@trie)
      large_set_trie = @trie
    end
  else
    if other.respond_to?(:lazy)
      small_set_pairs = other.lazy.map { |e| [e, nil] }
    else
      small_set_pairs = other.map { |e| [e, nil] }
    end
    large_set_trie = @trie
  end

  trie = large_set_trie.bulk_put(small_set_pairs)
  new_trie(trie)
end