Skip to main content
Module

x/fun/mod.ts>optic.viewer

A collection of algebraic data types, lenses, and schemables based on a light weight higher kinded type implementation. Written for deno.
Latest
function optic.viewer
import { optic } from "https://deno.land/x/fun@v2.0.0/mod.ts";
const { viewer } = optic;

Construct a Viewer<T, S, A> from a tag T and a view function that matches said tag. This is a raw constructor and is generally only useful if there is a case where a structure can be lensed into but not reconstructed or traversed. However, this is the core composable structure of optics, as they are primarily meant as a way to retrieve data from an existing structure.

Examples

The "Lens" viewer retrieves a single value that always exists.

import type { Pair } from "./pair.ts";

import * as O from "./optic.ts";
import * as P from "./pair.ts";

const fst = <A, B = unknown>() => O.viewer<O.LensTag, Pair<A, B>, A>(
  O.LensTag,
  P.getFirst,
);

const numPair = fst<number, number>();

const result1 = numPair.view(P.pair(1, 2)); // 1
const result2 = numPair.view(P.pair(2, 1)); // 2

The "Affine" viewer retrieves a single value that might exists.

import type { Either } from "./either.ts";

import * as O from "./optic.ts";
import * as E from "./either.ts";

const right = <R, L = unknown>() => O.viewer<O.AffineTag, Either<L, R>, R>(
  O.AffineTag,
  E.getRight,
);

const numberEither = right<number, string>();

const result1 = numberEither.view(E.right(1)); // Some(1)
const result2 = numberEither.view(E.left("Hello")); // None

The "Fold" viewer retrieves zero or more values as an Array.

import * as O from "./optic.ts";

const record = <A>() => O.viewer<O.FoldTag, Record<string, A>, A>(
  O.FoldTag,
  Object.values,
);

const numberRecord = record<number>();

const result = numberRecord.view({
  "one": 1,
  "two": 2,
}); // [1, 2]

Type Parameters

T extends Tag
S
A

Parameters

tag: T
view: (s: S) => $<ToKind<T>, [A, never, never]>