Functor: The "Mappable" Type Class

Name the map every container shares, and write one method that maps inside any of them.

What You'll Learn

  • Recognise map on Optional, List, CompletableFuture and MaybePath as one shape: Functor
  • Write a method that maps inside any container, through its Functor
  • Say what map promises, and what it leaves to each container
  • Check an instance against the two functor laws with hkj-test's FunctorLaws

See Example Code

The code on this page is FunctorBook.java, with totals from FoundationsIntroBook.java: the page includes both, so the build compiles and runs them. FunctorBookTest.java holds each claim the page makes, and FoundationsLawsBookTest.java checks the laws.


You have written this code:

optional.map(String::length);
list.stream().map(String::length).toList();
completableFuture.thenApply(String::length);
maybePath.map(String::length);

Four method calls, four containers, the same shape. Functor is the name of that shape: a container's map, keeping the two laws on this page. Most type classes in this chapter work this way, naming a capability you already use.

For one container, an Effect Path has its own map, as maybePath.map shows, and application code stays there. This page is for a method written once for any container, as the Foundations introduction's totals is.

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

import static org.higherkindedj.hkt.either.EitherKindHelper.EITHER;
import static org.higherkindedj.hkt.instances.Instances.functor;
import static org.higherkindedj.hkt.instances.Witnesses.either;
import static org.higherkindedj.hkt.instances.Witnesses.list;
import static org.higherkindedj.hkt.instances.Witnesses.maybe;
import static org.higherkindedj.hkt.list.ListKindHelper.LIST;
import static org.higherkindedj.hkt.maybe.MaybeKindHelper.MAYBE;

import java.math.BigDecimal;
import java.util.List;
import java.util.function.Function;
import org.higherkindedj.example.book.optics.cast.Order;
import org.higherkindedj.hkt.Functor;
import org.higherkindedj.hkt.Kind;
import org.higherkindedj.hkt.TypeArity;
import org.higherkindedj.hkt.WitnessArity;
import org.higherkindedj.hkt.either.Either;
import org.higherkindedj.hkt.maybe.Maybe;

What map promises

Functor<F> has one method, map:

public interface Functor<F extends WitnessArity<TypeArity.Unary>> {
  <A, B> Kind<F, B> map(Function<? super A, ? extends B> f, Kind<F, A> fa);
}

Given a function from A to B and a Kind<F, A>, it returns a Kind<F, B>. It applies the function to the values inside and keeps the container's shape:

The container holdsmap givesThe function runs
Three orders, in a ListA List of three resultsOnce for each order
One order, in a Just or a RightA Just or a Right of the resultOnce
A deferred order, in an IOA new IOEach time that IO runs
No value: a Nothing, an empty Optional or an empty ListThe container, still emptyNever
A failure: a Left or a failed TryThe same failureNever

The function sees the values, never the container. The table assumes a function that returns a value and does not throw. Values, never null says what each type does when it returns null.

One method for any container

The introduction's totals is written over Functor. It takes the Functor for F and calls map on it:

  // One method for any container F: the Functor passed in knows how to map inside F
  public static <F extends WitnessArity<TypeArity.Unary>> Kind<F, BigDecimal> totals(
      Functor<F> functor, Kind<F, Order> orders) {
    return functor.map(FoundationsIntroBook::total, orders);
  }

On containers that hold an order, it gives their totals, as the introduction shows. On containers that hold none, it keeps their shape:

    Maybe<Order> noOrder = Maybe.nothing();
    Maybe<BigDecimal> noTotal = MAYBE.narrow(totals(functor(maybe()), MAYBE.widen(noOrder)));
    // Nothing
    Either<String, Order> notFound = Either.left("order not found");
    Either<String, BigDecimal> sameLeft =
        EITHER.narrow(totals(functor(either()), EITHER.widen(notFound)));
    // Left(order not found)
    List<Order> noOrders = List.of();
    List<BigDecimal> noTotals = LIST.narrow(totals(functor(list()), LIST.widen(noOrders)));
    // []

Nothing in totals checks for an empty container or a failure. Each container's Functor knows what mapping means there: Maybe's gives back the Nothing, and Either's gives back the Left as it was. That is why totals is written once.

Two laws

A Functor keeps two laws, and you have assumed both whenever you called map. Together they say that map changes the values and never the container.

Laws

  • Identity: mapping a -> a changes nothing. map(a -> a, fa) equals fa.
  • Composition: two maps equal one map of both functions. map(g, map(f, fa)) equals map(f.andThen(g), fa).

Two containers are equal when they hold equal values in the same shape. For a deferred container such as IO, they are equal when running both gives equal results. Comparing them runs both, and repeats any effect they have, so check the laws with an IO that gives the same result on every run, as the test's IO.delay(() -> ORDER) does. Both laws assume functions that never return null, and Values, never null says what each type does with one.

FunctorLaws, in hkj-test's org.higherkindedj.hkt.laws package, checks both laws on any instance, your own included. You pass it the equality to use. KindEquivalence.byEqualsAfter, in org.higherkindedj.hkt.assertions, builds one from a function it applies to both sides, and compares the two results with equals: MAYBE::narrow unwraps a Maybe, and for an IO the function also runs it. A test of Maybe and IO uses these imports, with JUnit's:

import static org.higherkindedj.hkt.instances.Witnesses.io;
import static org.higherkindedj.hkt.instances.Witnesses.maybe;
import static org.higherkindedj.hkt.io.IOKindHelper.IO_OP;
import static org.higherkindedj.hkt.maybe.MaybeKindHelper.MAYBE;

import java.util.function.BiPredicate;
import java.util.stream.Stream;
import org.higherkindedj.example.book.optics.cast.Customer;
import org.higherkindedj.example.book.optics.cast.Order;
import org.higherkindedj.hkt.Functor;
import org.higherkindedj.hkt.Kind;
import org.higherkindedj.hkt.assertions.KindEquivalence;
import org.higherkindedj.hkt.instances.Instances;
import org.higherkindedj.hkt.io.IO;
import org.higherkindedj.hkt.io.IOKind;
import org.higherkindedj.hkt.laws.FunctorLaws;
import org.higherkindedj.hkt.maybe.Maybe;
import org.higherkindedj.hkt.maybe.MaybeKind;

The test checks both laws on a Just, a Nothing and an IO, where ORDER is any Order:

  static Stream<Kind<MaybeKind.Witness, Order>> maybeOrders() {
    return Stream.of(MAYBE.widen(Maybe.just(ORDER)), MAYBE.widen(Maybe.nothing()));
  }

  @ParameterizedTest
  @MethodSource("maybeOrders")
  @DisplayName("Maybe's Functor keeps both laws, on a Just and on a Nothing")
  void maybeFunctorLaws(Kind<MaybeKind.Witness, Order> fa) {
    Functor<MaybeKind.Witness> functor = Instances.functor(maybe());
    BiPredicate<Kind<MaybeKind.Witness, ?>, Kind<MaybeKind.Witness, ?>> same =
        KindEquivalence.byEqualsAfter(MAYBE::narrow);
    FunctorLaws.assertIdentity(functor, fa, same);
    FunctorLaws.assertComposition(functor, fa, Order::customer, Customer::email, same);
  }

  @Test
  @DisplayName("IO's Functor keeps both laws, comparing what each IO gives when it runs")
  void ioFunctorLaws() {
    Functor<IOKind.Witness> functor = Instances.functor(io());
    Kind<IOKind.Witness, Order> fa = IO_OP.widen(IO.delay(() -> ORDER));
    BiPredicate<Kind<IOKind.Witness, ?>, Kind<IOKind.Witness, ?>> sameResult =
        KindEquivalence.byEqualsAfter(kind -> IO_OP.narrow(kind).unsafeRunSync());
    FunctorLaws.assertIdentity(functor, fa, sameResult);
    FunctorLaws.assertComposition(functor, fa, Order::customer, Customer::email, sameResult);
  }

Back to the one-liner

  static EitherPath<OrderError, Order> changeEmail(
      OrderRepository orders, UUID id, String newEmail) {
    return orders
        .find(id)
        .toEitherPath(OrderError.notFound(id))
        .map(order -> OrderFocus.customer().email().value().set(newEmail, order))
        .via(orders::save);
  }

.map(...) is the line's Functor layer: on a Right it changes the order's email, and a Left passes through untouched. Two encodings, one algebra matches it to Functor's map over Kind.

Things people get wrong

Common Misunderstandings

  • "Mapping iterates." Only over a collection. map runs the function at most once on an Optional, and on an Either only for a Right.
  • "map runs the function now." Not on a deferred container. IO's map builds a new IO, and the function runs only when that IO runs. Functor promises the shape, not when the function runs.
  • "It is Stream.map with extra steps." The aim is one method for every container that can be mapped. You pay some ceremony at the boundary, the widen and narrow, so that the method's body is written once.
  • "map can run a step that fails." A function that returns an Either gives an Either inside an Either, such as Right(Left(order already shipped)). A step that can fail needs flatMap, which Monad teaches.

You can ship now

You can now write a method that maps inside any container, as totals does, and check an instance of your own against the two laws. The rest of this page is for which types have a Functor, and what builds on it.

Checkpoint: map over an Invalid

With Validated's instance, you map LineItem::quantity over a Validated that is Invalid([SKU is blank]). What comes back, and does LineItem::quantity run?

Answer and why

The same Invalid([SKU is blank]), and the function never runs. map changes the values a container holds and keeps its shape. An Invalid holds no line item, so there is nothing to change.

Where this lives: What map promises.

Checkpoint: the identity law on IO

You check IO's Functor against the identity law, with an equality built by KindEquivalence.byEqualsAfter(IO_OP::narrow). Does FunctorLaws.assertIdentity pass?

Answer and why

No. map(a -> a, io) builds a new IO, so comparing the two IO objects with equals fails, though both give the same result. For a deferred container, two values are equal when running both gives equal results, so the equality must run them, on an IO that gives the same result every run: byEqualsAfter(kind -> IO_OP.narrow(kind).unsafeRunSync()).

Where this lives: Two laws.


The fine print

Which types have a Functor

TypesTheir Functor comes from
Every token in WitnessesTheir Monad, so Instances.functor(token) always succeeds
Validated, Writer, EitherOrBoth and the transformersTheir Monad, from Instances with its argument, such as Instances.validated(semigroup)
FreeIts Monad, built with new FreeMonad<>()
Const, FreeAp and FetchAn Applicative, with no Monad
EitherFEitherFFunctor alone
CoyonedaCoyonedaFunctor, which gives a Functor to a type that has none, as Coyoneda shows

What builds on Functor

  • Applicative extends Functor, and Monad extends Applicative. Every instance on the next pages has this map.
  • Traverse extends both Functor and Foldable. Foldable and Traverse covers it.
  • Bifunctor is not a Functor. It maps a type with two parameters, such as both sides of an Either, as Bifunctor shows.

See Also

Further Reading

Hands-On Learning

Practise Functor mapping in Tutorial 02: Functor Mapping (7 exercises).


Previous: Obtaining Instances Next: Applicative