Skip to main content
Module

x/fun/mod.ts>optic.compose

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

Compose two optics, aligning their tag and building the composition using natural transformations and monadic chaining for the view function and using direct composition for the modify function.

The general algorithm for optic composition in fun is:

  1. Finding the alignment of them, which is Max<first, second> where Fold > AffineFold > Get
  2. Cast both optics to the alignment tag, one cast will always be a noop.
  3. Construct a new optic by chaining the view functions first to second and composing the modify functions second to first.

Examples

Example 1

import * as O from "./optic.ts";
import { pipe } from "./fn.ts";

const even = O.fromPredicate((n: number) => n % 2 === 0);
const positive = O.fromPredicate((n: number) => n > 0);

const evenPos = pipe(
  even,
  O.compose(positive),
);
const addTwo = pipe(evenPos, O.modify(n => n + 2));

const result1 = pipe(evenPos, O.view(0)); // None
const result2 = pipe(evenPos, O.view(1)); // None
const result3 = pipe(evenPos, O.view(2)); // Some(2)
const result4 = addTwo(0); // 0
const result5 = addTwo(1); // 1
const result6 = addTwo(2); // 2

Type Parameters

V extends Tag
A
I

Parameters

second: Optic<V, A, I>

Returns

<U extends Tag, S>(first: Optic<U, S, A>) => Optic<Align<U, V>, S, I>