Skip to content

unifiers ref()

Eugene Lazutkin edited this page May 8, 2026 · 4 revisions

Creates a reference variable that binds to a specific value during unification.

Introduction

The ref unifier is useful for cross-pattern matching where you want to ensure two different parts of a pattern have the same value. It binds a variable to a value and then continues unification.

import ref from 'deep6/unifiers/ref.js';
import {variable} from 'deep6/env.js';
import unify from 'deep6/unify.js';

const name = variable('name');
const pattern = {
  firstName: ref(name, 'John'),
  lastName: ref(name, 'John'), // Must match same value
  profile: {
    displayName: name // Captures the value
  }
};

unify({firstName: 'John', lastName: 'John', profile: {displayName: 'John'}}, pattern);
// All references to 'name' must be 'John'

API

ref(variable, value)

Arguments:

  • variable — a required variable name (string) or Variable instance to reference.
  • value — a required value to bind to the variable.

Returns a Ref unifier instance. The Ref class is exported as a named export of the module, and is also accessible as ref.Ref.

import ref, {Ref} from 'deep6/unifiers/ref.js';

const r = ref('name', 42);
r instanceof Ref; // true

Class: Ref

Extends Variable.

Properties

  • variable — the referenced Variable instance.
  • value — the value to bind to the variable.

Methods

  • unify(val, ls, rs, env) — binds the referenced variable to both value and val.
    • Always returns true.
    • Pushes bindings to the stacks: value = val and variable = val.

Examples

import ref from 'deep6/unifiers/ref.js';
import {variable} from 'deep6/env.js';
import {match} from 'deep6';

// Ensure two fields have the same value
const userPattern = {
  email: ref('contact', 'user@example.com'),
  contact: {
    email: variable('contact')
  }
};

match(
  {
    email: 'user@example.com',
    contact: {email: 'user@example.com'}
  },
  userPattern
); // true

// Using with variable instances
const ageVar = variable('age');
const ageRef = ref(ageVar, 25);

Clone this wiki locally