Skip to content

unify()

Eugene Lazutkin edited this page Jan 11, 2022 · 4 revisions

This is the most important algorithm of this package. It implements the first-order unification algorithm using environments and variables.

The unification can be imagined as an advanced version of deep equivalence. It works like that when no variables are used. With variables, it allows ignoring parts of objects or saving them to be retrieved later.

The function can deal with incomplete (open) objects and circular references (see below for more details).

Out of the box it can compare all builtin JavaScript types (numbers, strings, boolean values, symbols, bigints, undefined values), arrays, common objects, and objects of the following builtin classes: Date, RegExp, Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, BigInt64Array, BigUint64Array, DataView, ArrayBuffer, Set, Map. These list can be extended for any custom class.

It is defined in unify and can be accessed like that:

import unify from 'deep6/unify.js';

The main module provides handy helpers based on unify():

Introduction

import unify, {open, variable, any} from 'deep6/unify.js';

const x = {a: 1, b: 2, c: ['hi!', 42, null, {}]};

// deep equivalence
!!unify(x, {b: 2, a: 1, c: ['hi!', 42, null, {}]}); // true

// pattern matching
!!unify(x, open({a: 1})); // true
!!unify(x, open({b: 2})); // true
!!unify(x, open({z: 1})); // false
!!unify(x, open({a: 2})); // false

const z = {}, w = {};
z.z = z;
w.z = w;

// circular dependencies
!!unify(z, w); // true

const v1 = variable(), v2 = variable(), v3 = variable();

// variables
const env = unify(x, {a: v1, b: v2, c: v3}); // truth
v1.get(env); // 1
v2.get(env); // 2
v3.get(env); // ['hi!', 42, null, {}]

// anyvar
!!unify(x, {b: any, a: 1, c: any}); // true
Clone this wiki locally