| title | Type Classes for Equality, Ordering, and Hashing with Data.Class | |||||||
|---|---|---|---|---|---|---|---|---|
| id | data-class | |||||||
| skillLevel | intermediate | |||||||
| applicationPatternId | core-concepts | |||||||
| summary | Use Data.Class to derive and implement type classes for equality, ordering, and hashing, enabling composable and type-safe abstractions. | |||||||
| tags |
|
|||||||
| rule |
|
|||||||
| related |
|
|||||||
| author | PaulJPhilp | |||||||
| lessonOrder | 17 |
Use Data.Class to derive or implement type classes for equality, ordering, and hashing for your custom data types.
This enables composable, type-safe abstractions and allows your types to work seamlessly with Effect’s collections and algorithms.
Type classes like Equal, Order, and Hash provide a principled way to define how your types are compared, ordered, and hashed.
This is essential for using your types in sets, maps, and for sorting or deduplication.
import { Data, Equal, HashSet } from "effect";
// Define custom data types with structural equality
const user1 = Data.struct({ id: 1, name: "Alice" });
const user2 = Data.struct({ id: 1, name: "Alice" });
const user3 = Data.struct({ id: 2, name: "Bob" });
// Data.struct provides automatic structural equality
console.log(Equal.equals(user1, user2)); // true (same structure)
console.log(Equal.equals(user1, user3)); // false (different values)
// Use in a HashSet (works because Data.struct implements Equal)
const set = HashSet.make(user1);
console.log(HashSet.has(set, user2)); // true (structural equality)
// Create an array and use structural equality
const users = [user1, user3];
console.log(users.some((u) => Equal.equals(u, user2))); // trueExplanation:
Data.Class.getEqualderives an equality type class for your data type.Data.Class.getOrderderives an ordering type class, useful for sorting.Data.Class.getHashderives a hash function for use in sets and maps.- These type classes make your types fully compatible with Effect’s collections and algorithms.
Relying on reference equality, ad-hoc comparison functions, or not providing type class instances for your custom types, which can lead to bugs and inconsistent behavior in collections.