# knotkit/e-graph

> Propagates equalities through expressions and extracts a minimum-cost equivalent expression

## Use

```ts
import { eGraph } from 'knotkit/e-graph'

const graph = eGraph()
const x = graph.add('x')
const plusZero = graph.add('+', [x, graph.add('0')])
const left = graph.add('sin', [x])
const right = graph.add('sin', [plusZero])

graph.equivalent(left, right) // false
graph.unite(x, plusZero) // the caller supplies x = x + 0
graph.equivalent(left, right) // true, by congruence
```

```ts
const product = graph.add('×', [graph.add('2'), x])
const sum = graph.add('+', [x, x])
graph.unite(product, sum)

// A printer counts occurrences of x.
graph.extract(product, (op) => Number(op === 'x')).operator // '×'
// A code generator charges five units for multiplication and one for every other operator.
graph.extract(product, (op) => (op === '×' ? 5 : 1)).operator // '+'
```

## What it solves

* share repeated subexpressions even when their operands were built from different equivalent terms
* recognize that replacing an operand with an equal operand preserves an expression
* select the cheapest equivalent expression under a caller's operator prices

## Choose a layout

| Factory                    | Choose when                                                                                                      | Cost                                                                             |
| -------------------------- | ---------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| `eGraph`kind `hash-consed` | the caller supplies term equalities and needs an immediate equivalence query or a minimum-cost finite expression | an effective merge rescans stored terms until the congruence relation stabilizes |

[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/e-graph/README.md#performance)

## Worked example

* Declaring x + 0 equal to x also equates all 6 nested sin pairs.
* Multiplication price 1 selects × (cost 3). Price 6 selects + (cost 5).
* Prices count each occurrence. Here x costs 2, addition costs 1, and literals cost 0.

Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/e-graph/demo.ts) against `knotkit/e-graph`.

## API

| Export                                                   | Returns      | Does                                                                  |
| -------------------------------------------------------- | ------------ | --------------------------------------------------------------------- |
| [`eGraph`](/reference/knotkit/e-graph/functions/egraph/) | `EGraph<Op>` | Interns ordered terms and eagerly closes each merge under congruence. |

Cost per member. Open a row for every operation.

`eGraph` 5 members

| Member       | Cost                                                                   |
| ------------ | ---------------------------------------------------------------------- |
| `size`       | O(1)                                                                   |
| `add`        | O(k \* alpha(n)) amortized for k children                              |
| `unite`      | O(n \* (n + m) \* alpha(n)) per effective merge, O(alpha(n)) otherwise |
| `equivalent` | O(alpha(n)) amortized                                                  |
| `extract`    | O((n + m) \* alpha(n) + n log(n + 1)), excluding the price callback    |

## What you pass in

| Input                               | Type                       | Get one from |
| ----------------------------------- | -------------------------- | ------------ |
| local price per operator occurrence | `(operator: Op) => number` | `the caller` |

## Errors

Every error this module throws is `EGraphInvalidInputError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.

* `FOREIGN_CLASS` `INVALID_COST` `COST_OVERFLOW`

## When not to use it

| If you need to…                                                                  | Use instead                                      |
| -------------------------------------------------------------------------------- | ------------------------------------------------ |
| merge groups of opaque values                                                    | [`knotkit/disjoint-set`](/modules/disjoint-set/) |
| discover substitutions by pattern matching and repeatedly applying rewrite rules | egglog                                           |

## Performance

Measured by the suite in [`packages/e-graph/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/e-graph/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.

## Prompt an agent

Prompt · knotkit/e-graphCopy prompt

```
Use knotkit/e-graph for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/e-graph'.

Exports:
- `eGraph` → `EGraph<Op>`: Interns ordered terms and eagerly closes each merge under congruence.

Pick the layout by these rules:
- `eGraph` (kind 'hash-consed') when the caller supplies term equalities and needs an immediate equivalence query or a minimum-cost finite expression

Inputs and their sources:
- local price per operator occurrence: `(operator: Op) => number` from `the caller`

Use something else when:
- merge groups of opaque values → knotkit/disjoint-set
- discover substitutions by pattern matching and repeatedly applying rewrite rules → egglog

Errors are EGraphInvalidInputError with a `code` property. Branch on `error.code`, never on the message.

Full page: https://knotkit.jkomyno.dev/modules/e-graph.md
Types: node_modules/knotkit/e-graph/ and https://knotkit.jkomyno.dev/reference/knotkit/e-graph/
```

## See also

* [API reference](/reference/knotkit/e-graph/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/e-graph/knotkit.capability.json)this page as JSON, also in the installed package
* [Edit this page on GitHub](https://github.com/jkomyno/knotkit/edit/main/packages/e-graph/knotkit.capability.json)suggest a change to the source record
