Skip to content

Instantly share code, notes, and snippets.

@mjwillson
Created November 13, 2008 17:05
Show Gist options
  • Save mjwillson/24501 to your computer and use it in GitHub Desktop.
Save mjwillson/24501 to your computer and use it in GitHub Desktop.
Simple Ruby class for an extensionally-specified Equivalence Relation with fast lookup
require 'set'
class EquivalenceRelation
def initialize
@equivalence_class_by_member = {}
end
def declare_equivalent(*items)
combined_equivalence_class = items.map {|item| equivalence_class_of(item)}.inject(Set.new) {|accum,set| accum.union(set)}
combined_equivalence_class.each {|member| @equivalence_class_by_member[member] = combined_equivalence_class}
end
def equivalence_class_of(x)
@equivalence_class_by_member[x] || Set.new([x])
end
def [](x)
equivalence_class_of(x) - [x]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment