Skip to content

Hash

Hash computes a numeric bucket fingerprint for Effect's equality-aware collections (HashSet, HashMap). Implement [Hash.symbol] whenever you implement Equal.Equal so equal instances always hash identically.

RuleRequirement
ConsistencyEqual.equals(a, b) implies Hash.hash(a) === Hash.hash(b)
Return type[Hash.symbol]() must synchronously return a number (never an effect method)
StabilityNever mutate fields included in the hash after inserting into a collection

Connecting hashing to equality

const first = { section: "billing", page: 2 }
const same = { section: "billing", page: 2 }
Equal.equals(first, same) // true
Hash.hash(first) === Hash.hash(same) // true
// Run in an effect function: try Console.log(try Effect.try(() => JSON.stringify([Equal.equals(first, same), Hash.hash(first) === Hash.hash(same)])))
// Output: [true,true]

Equal values must produce identical hashes, though distinct values may collide in the same bucket (collections confirm matches with Equal.equals). Treat hashes as in-memory lookup hints, never as cryptographic digests or persistent identifiers.

Implementing the hashing protocol

class GridCell implements Equal.Equal {
  constructor(readonly row: number, readonly column: number) {}
 
  [Equal.symbol](other: Equal.Equal): boolean {
    return other instanceof GridCell &&
      this.row === other.row && this.column === other.column
  }
 
  [Hash.symbol]() {
    return Hash.hash([this.row, this.column])
  }
}
 
Hash.hash(new GridCell(3, 7)) === Hash.hash(new GridCell(3, 7)) // true
Equal.equals(new GridCell(3, 7), new GridCell(3, 8)) // false
// Run in an effect function: try Console.log(try Effect.try(() => JSON.stringify([Hash.hash(new GridCell(3, 7)) === Hash.hash(new GridCell(3, 7)), Equal.equals(new GridCell(3, 7), new GridCell(3, 8))])))
// Output: [true,false]

Hash.hash accepts primitives and structural tuples, so delegating [Hash.symbol]() to Hash.hash([field1, field2]) is usually sufficient. Because Equal.Equal extends Hash.Hash, [Hash.symbol]() must be a synchronous plain method returning a number.

Keeping equal values hash-consistent

const first = new GridCell(3, 7)
const equivalent = new GridCell(3, 7)
const cells = HashSet.make(first, equivalent)
HashSet.size(cells) // 1
Hash.hash(first) === Hash.hash(equivalent) // true
// Run in an effect function: try Console.log(try Effect.try(() => JSON.stringify([HashSet.size(cells), Hash.hash(first) === Hash.hash(equivalent)])))
// Output: [1,true]

Hash only fields compared by [Equal.symbol]: including an ignored field places equal values in different buckets and breaks lookup, whereas omitting an identity field remains correct at the cost of extra collisions. Keep hashed fields immutable after insertion because hashes may be cached.


The matching Effect page: effect.website/docs/v4/trait/hash