Skip to content

Latest commit

 

History

History
73 lines (58 loc) · 2.51 KB

File metadata and controls

73 lines (58 loc) · 2.51 KB
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
Data.Class
type-class
equality
ordering
hashing
data-type
effect
rule
description
Use Data.Class to define and derive type classes for your data types, supporting composable equality, ordering, and hashing.
related
data-struct
data-tuple
data-array
author PaulJPhilp
lessonOrder 17

Type Classes for Equality, Ordering, and Hashing with Data.Class

Guideline

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.

Rationale

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.

Good Example

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))); // true

Explanation:

  • Data.Class.getEqual derives an equality type class for your data type.
  • Data.Class.getOrder derives an ordering type class, useful for sorting.
  • Data.Class.getHash derives a hash function for use in sets and maps.
  • These type classes make your types fully compatible with Effect’s collections and algorithms.

Anti-Pattern

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.