Equivalence

On this page

Generating Equivalences

The Equivalence.make function allows you to generate an Equivalence based on a schema definition. This function is designed to compare data structures for equivalence according to the rules defined in the schema.

Example

ts
import { Equivalence, Schema } from "@effect/schema"
 
const Person = Schema.Struct({
name: Schema.String,
age: Schema.Number
})
 
const PersonEquivalence = Equivalence.make(Person)
 
const john = { name: "John", age: 23 }
const alice = { name: "Alice", age: 30 }
 
console.log(PersonEquivalence(john, { name: "John", age: 23 })) // Output: true
console.log(PersonEquivalence(john, alice)) // Output: false
ts
import { Equivalence, Schema } from "@effect/schema"
 
const Person = Schema.Struct({
name: Schema.String,
age: Schema.Number
})
 
const PersonEquivalence = Equivalence.make(Person)
 
const john = { name: "John", age: 23 }
const alice = { name: "Alice", age: 30 }
 
console.log(PersonEquivalence(john, { name: "John", age: 23 })) // Output: true
console.log(PersonEquivalence(john, alice)) // Output: false

Customizing Equivalence Generation

You can define how equivalence is generated by utilizing the equivalence annotation in your schema definitions.

Example

ts
import { Equivalence, Schema } from "@effect/schema"
 
const schema = Schema.String.annotations({
equivalence: (/**typeParameters**/) => (s1, s2) =>
s1.charAt(0) === s2.charAt(0)
})
 
console.log(Equivalence.make(schema)("aaa", "abb")) // Output: true
ts
import { Equivalence, Schema } from "@effect/schema"
 
const schema = Schema.String.annotations({
equivalence: (/**typeParameters**/) => (s1, s2) =>
s1.charAt(0) === s2.charAt(0)
})
 
console.log(Equivalence.make(schema)("aaa", "abb")) // Output: true

In this setup, the equivalence annotation takes any type parameters provided (typeParameters) and two values for comparison, returning a boolean based on the desired condition of equivalence.