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.
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.
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