index.rd

[Japanese]

# Finite Set

    Version: 0.56.27 (2002.03.11)

    Author: Shin-ichiro HARA (sinara@blade.nagaokaut.ac.jp)

This is a library for Sets and Maps.

This is made as a part of the library "Algebra" originally.

## 1. Install

Copy lib/*.rb to the directory where Ruby can load.

## 2. Usage

To create a Set object, use `Set[]`, then you can use the fundamental operations union, intersection and so on. The criteria for identity of Set is the value of eql?. The order of the elements is indefinite. Use `Map[]` to get the map.

Exameple:

    require "finite-set"
    include Algebra
    s = Set[3, 0, 1, 2, 3]
    p s #=> {0, 1, 2, 3}

    t = Set[2, 3, 4, 5]
    p s & t #=> {2, 3}
    p s | t #=> {5, 0, 1, 2, 3, 4}

    require "finite-map"
    m = Map[0 => 10, 1 => 11, 2 => 21, 3 => 31]
    p m.image(s) #=> {10, 31, 21, 11}

## 3. Notice

Set and Map hold the data as the Hash objects. So, the identity of objects are done not by == but by eql?. If you construct sets of which elements are the instances of user defined classes, you must re-define eql? and hash adequately. Especially,

if a.eql?(b) is true then a.hash == b.hash must be true.

The following is the example for the 2-dimensional vector.

    Exameple:
       class Vector
         attr_accessor :x, :y
         def initialize(x, y)
           @x, @y = x, y
         end
         def eql?(other)
           @x == other.x and @y == other.y
         end
         alias == eql?
         def hash
           @x.hash ^ @y.hash
         end
         def inspect
           "[#{@x.inspect}, #{@y.inspect}]"
         end
       end
       v0, v1 = Vector.new(0, 1), Vector.new(1, 2)
       s = Set[v0, v1]
       p s.has? Vector.new(0, 1) #=> true

For built-in class, eql? and hash are already defined.

Even if all elements of set are of built-in class, when the conditions are chaned, you may not get the elements of the set. This is overcomed by use of Set#rehash.

    Exameple:
      a = [0, 1]
      b = [1, 2]
      s = Set[a, b]
      a[0] = 10
      p s #=> {[1, 2], [10, 1]}
      p s.has? [10, 1] #=> false
      s.rehash
      p s.has? [10, 1] #=> true

## 4. Manuals

- Algebra::Set (Sets)
- Algebra::Map (Maps)