Profunctor: Building Adaptable Data Pipelines

Adapt what a function takes with lmap, what it gives with rmap, and both at once with dimap.

"It's a poor sort of memory that only works backwards," the Queen remarked.

— Lewis Carroll, Through the Looking-Glass

A profunctor's adapters point both ways. rmap's goes forwards, from the old output to the new one, and lmap's goes backwards, from the new input to the old one.

What You'll Learn

  • Adapt a function's input with lmap, its output with rmap, and both with dimap
  • Say why lmap's function goes from the new input to the old one, which is what contravariant means
  • Write the same adaptation with Function's compose and andThen, and know which to reach for
  • Say how Higher-Kinded-J's optics relate to Profunctor
  • Check the two Profunctor laws by hand

See Example Code

The code on this page is ProfunctorBook.java, which uses lineTotal from MonoidBook.java: the page includes it, so the build compiles and runs it. ProfunctorBookTest.java holds what the page says, and FoundationsLawsBookTest.java checks the laws. ProfunctorExample.java adapts functions for an API, a validation pipeline and a data transformation.


A function has two ends

You adapt a Function<A, B> at both ends already. andThen runs a function after it, from B to the new output. compose runs one before it, from the new input to A. The second points backwards: the input type changes from A to the new one, but the function you supply goes from the new input to A. So a function's input side is contravariant and its output side covariant, as variance in the glossary explains. A Bifunctor's two sides are both outputs.

For one function, compose and andThen are all you need, as Plain Java does the same shows. On an Effect Path, a ReaderPath is a function from an environment: its local adapts the input, and its map the output. Profunctor names the two adaptations for any type with an input and an output:

public interface Profunctor<P extends WitnessArity<TypeArity.Binary>> {
  <A, B, C, D> Kind2<P, C, D> dimap(
      Function<? super C, ? extends A> f, Function<? super B, ? extends D> g, Kind2<P, A, B> pab);

  default <A, B, C> Kind2<P, C, B> lmap(Function<? super C, ? extends A> f, Kind2<P, A, B> pab) {
    return dimap(f, Function.identity(), pab);
  }

  default <A, B, C> Kind2<P, A, C> rmap(Function<? super B, ? extends C> g, Kind2<P, A, B> pab) {
    return dimap(Function.identity(), g, pab);
  }
}

lmap and rmap are dimap with Function.identity() on the end they leave alone. For a function, dimap(f, g, p) runs f, then p, then g. Higher-Kinded-J ships one instance, FunctionProfunctor.INSTANCE, for Function, and Instances has no entry for it.

Adapting a function

The code on this page uses these imports, with LineItem from the order records the Optics chapter introduces:

import static org.higherkindedj.hkt.func.FunctionKindHelper.FUNCTION;

import java.math.BigDecimal;
import java.util.function.Function;
import org.higherkindedj.example.book.foundations.monoid.MonoidBook;
import org.higherkindedj.example.book.optics.cast.LineItem;
import org.higherkindedj.hkt.Kind2;
import org.higherkindedj.hkt.func.FunctionKind;
import org.higherkindedj.hkt.func.FunctionProfunctor;

Semigroup and Monoid's lineTotal takes a LineItem and gives its price times its quantity. The warehouse's feed sends each line as text, and a card payment is taken in pence:

  // A line as the warehouse's feed sends it, such as "BULB,4,2.50"
  public static LineItem parse(String feedLine) {
    String[] fields = feedLine.split(",");
    return new LineItem(fields[0], Integer.parseInt(fields[1]), new BigDecimal(fields[2]));
  }

  // A total in pence, as a card payment is taken
  public static int pence(BigDecimal total) {
    return total.movePointRight(2).intValueExact();
  }

lmap lets lineTotal take the feed's text, rmap gives its result in pence, and dimap does both:

    FunctionProfunctor profunctor = FunctionProfunctor.INSTANCE;
    Kind2<FunctionKind.Witness, LineItem, BigDecimal> total = FUNCTION.widen(MonoidBook::lineTotal);

    // lmap: the function now takes the feed's text, and parses it before it totals
    Function<String, BigDecimal> fromFeed =
        FUNCTION.getFunction(profunctor.lmap(ProfunctorBook::parse, total));
    BigDecimal bulbs = fromFeed.apply("BULB,4,2.50");
    // 10.00

    // rmap: the function now gives its total in pence
    Function<LineItem, Integer> inPence =
        FUNCTION.getFunction(profunctor.rmap(ProfunctorBook::pence, total));
    int lamp = inPence.apply(new LineItem("LAMP", 1, new BigDecimal("40.00")));
    // 4000

    // dimap: both at once, from the feed's text to pence
    Function<String, Integer> feedToPence =
        FUNCTION.getFunction(profunctor.dimap(ProfunctorBook::parse, ProfunctorBook::pence, total));
    int bulbsInPence = feedToPence.apply("BULB,4,2.50");
    // 1000

FunctionProfunctor's lmap, rmap and dimap run nothing when you call them. Each builds a new function, and the adapters run every time that function is applied.

Plain Java does the same

For one function you hold, Function's own compose and andThen give the same result, with no Kind2 to widen or unwrap:

    Function<LineItem, BigDecimal> lineTotal = MonoidBook::lineTotal;
    Function<String, Integer> plainJava =
        lineTotal.compose(ProfunctorBook::parse).andThen(ProfunctorBook::pence);
    int samePence = plainJava.apply("BULB,4,2.50");
    // 1000

Plain Java wins here

To adapt one Function, use compose and andThen. Profunctor earns its place only in code written for any type with an input and an output, such as a parser or an encoder of your own that you give an instance.

Optics adapt the same way, but are not built on it

Higher-Kinded-J's optics are van Laarhoven optics. Each is built on one method, modifyF, which runs a function on the part the optic focuses on inside a Functor or Applicative, and rebuilds the whole. An Optic's modifyF takes an Applicative, and a Lens also has one that needs only a Functor.

Optic has its own contramap, map and dimap, which adapt an optic's source and result as lmap, rmap and dimap adapt a function. Profunctor Optics shows them: that page is named for these adapters, not for the way the optics are built. Optic is not a Profunctor instance.

Two laws

A Profunctor keeps two laws: adapting with identities changes nothing, and two adaptations in turn equal one.

Laws

  • Identity: adapting both ends with a -> a changes nothing. dimap(a -> a, b -> b, p) equals p.
  • Composition: two dimaps equal one dimap of both pairs. dimap(f2, g2, dimap(f1, g1, p)) equals dimap(f2.andThen(f1), g1.andThen(g2), p). The input adapters join in the opposite order to the output ones, since the outer dimap's f2 runs first.

Two functions are equal when they give equal results for every input. A test cannot try every input, so it tries a few. The laws assume functions that never return null.

Checking the Profunctor laws with hkj-test is not supported yet, so the test checks them by hand, on a few inputs. It uses these imports, with JUnit's:

import static org.assertj.core.api.Assertions.assertThat;
import static org.higherkindedj.hkt.func.FunctionKindHelper.FUNCTION;

import java.math.BigDecimal;
import java.util.List;
import java.util.function.Function;
import org.higherkindedj.example.book.foundations.monoid.MonoidBook;
import org.higherkindedj.example.book.foundations.profunctor.ProfunctorBook;
import org.higherkindedj.example.book.optics.cast.LineItem;
import org.higherkindedj.hkt.Kind2;
import org.higherkindedj.hkt.func.FunctionKind;
import org.higherkindedj.hkt.func.FunctionProfunctor;
  // Two functions are equal when they give equal results for every input; the test tries several
  <A, B> void assertSameResults(List<A> inputs, Function<A, B> expected, Function<A, B> actual) {
    for (A input : inputs) {
      assertThat(actual.apply(input)).isEqualTo(expected.apply(input));
    }
  }

  @Test
  @DisplayName("Function's Profunctor keeps both laws, on every input tried")
  void functionProfunctorLaws() {
    FunctionProfunctor profunctor = FunctionProfunctor.INSTANCE;
    Function<LineItem, BigDecimal> lineTotal = MonoidBook::lineTotal;
    Kind2<FunctionKind.Witness, LineItem, BigDecimal> p = FUNCTION.widen(lineTotal);

    assertSameResults(
        MonoidBook.LINES,
        lineTotal,
        FUNCTION.getFunction(
            profunctor.dimap(Function.<LineItem>identity(), Function.<BigDecimal>identity(), p)));

    Function<String, LineItem> f1 = ProfunctorBook::parse;
    Function<String, String> f2 = String::strip;
    Function<BigDecimal, Integer> g1 = ProfunctorBook::pence;
    Function<Integer, String> g2 = pence -> pence + "p";
    assertSameResults(
        List.of(" BULB,4,2.50", "LAMP,1,40.00 "),
        FUNCTION.getFunction(profunctor.dimap(f2.andThen(f1), g1.andThen(g2), p)),
        FUNCTION.getFunction(profunctor.dimap(f2, g2, profunctor.dimap(f1, g1, p))));
  }

Things people get wrong

Common Misunderstandings

  • "lmap's function runs after the original." It runs before, turning the input you have into the one the original takes.
  • "Either is a profunctor." Both of its sides are results, so it is a Bifunctor. A profunctor's first side is an input.
  • "Higher-Kinded-J's optics are profunctor optics." They are van Laarhoven optics. Optic.dimap has the shape of Profunctor's dimap, as a method on the optic.
  • "dimap runs its adapters when you call it." FunctionProfunctor's dimap builds a new function, and the adapters run each time that function is applied.

See Also

Further Reading

  • Mojang, DataFixerUpper: Minecraft's Java library for migrating saved data, built on profunctor optics
  • Hablapps, Don't Fear the Profunctor Optics: an introduction to profunctor optics, the encoding Higher-Kinded-J's optics do not use

Previous: Bifunctor Next: For with Optics