Skip to content

Latest commit

 

History

History
68 lines (53 loc) · 1.95 KB

File metadata and controls

68 lines (53 loc) · 1.95 KB
title Working with Tuples using Data.tuple
id data-tuple
skillLevel beginner
applicationPatternId core-concepts
summary Use Data.tuple to create immutable, type-safe tuples that support value-based equality and pattern matching.
tags
Data.tuple
tuple
structural-equality
immutable
data-type
effect
rule
description
Use Data.tuple to define tuples whose equality is based on their contents, enabling safe and predictable comparisons and pattern matching.
related
data-struct
data-array
author PaulJPhilp
lessonOrder 25

Working with Tuples using Data.tuple

Guideline

Use Data.tuple to create immutable, type-safe tuples that support value-based equality and pattern matching.
This is useful for modeling fixed-size, heterogeneous collections of values in a safe and expressive way.

Rationale

JavaScript arrays are mutable and compared by reference, which can lead to bugs in value-based logic.
Data.tuple provides immutable tuples with structural equality, making them ideal for domain modeling and functional programming patterns.

Good Example

import { Data, Equal } from "effect";

// Create two structurally equal tuples
const t1 = Data.tuple(1, "Alice");
const t2 = Data.tuple(1, "Alice");

// Compare by value, not reference
const areEqual = Equal.equals(t1, t2); // true

// Use tuples as keys in a HashSet or Map
import { HashSet } from "effect";
const set = HashSet.make(t1);
console.log(HashSet.has(set, t2)); // true

// Pattern matching on tuples
const [id, name] = t1; // id: number, name: string

Explanation:

  • Data.tuple creates immutable tuples with value-based equality.
  • Useful for modeling pairs, coordinates, or any fixed-size, heterogeneous data.
  • Supports safe pattern matching and collection operations.

Anti-Pattern

Using plain arrays for value-based logic or as keys in sets/maps, which compares by reference and can lead to incorrect behavior.