Functor: The "Mappable" Type Class
Name the map every container shares, and write one method that maps inside any of them.
- Recognise
maponOptional,List,CompletableFutureandMaybePathas one shape:Functor - Write a method that maps inside any container, through its
Functor - Say what
mappromises, and what it leaves to each container - Check an instance against the two functor laws with
hkj-test'sFunctorLaws
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 holds | map gives | The function runs |
|---|---|---|
Three orders, in a List | A List of three results | Once for each order |
One order, in a Just or a Right | A Just or a Right of the result | Once |
A deferred order, in an IO | A new IO | Each time that IO runs |
No value: a Nothing, an empty Optional or an empty List | The container, still empty | Never |
A failure: a Left or a failed Try | The same failure | Never |
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.
- Identity: mapping
a -> achanges nothing.map(a -> a, fa)equalsfa. - Composition: two maps equal one map of both functions.
map(g, map(f, fa))equalsmap(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
- "Mapping iterates." Only over a collection.
mapruns the function at most once on anOptional, and on anEitheronly for aRight. - "
mapruns the function now." Not on a deferred container.IO'smapbuilds a newIO, and the function runs only when thatIOruns.Functorpromises the shape, not when the function runs. - "It is
Stream.mapwith extra steps." The aim is one method for every container that can be mapped. You pay some ceremony at the boundary, thewidenandnarrow, so that the method's body is written once. - "
mapcan run a step that fails." A function that returns anEithergives anEitherinside anEither, such asRight(Left(order already shipped)). A step that can fail needsflatMap, which Monad teaches.
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.
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
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.
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
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
| Types | Their Functor comes from |
|---|---|
Every token in Witnesses | Their Monad, so Instances.functor(token) always succeeds |
Validated, Writer, EitherOrBoth and the transformers | Their Monad, from Instances with its argument, such as Instances.validated(semigroup) |
Free | Its Monad, built with new FreeMonad<>() |
Const, FreeAp and Fetch | An Applicative, with no Monad |
EitherF | EitherFFunctor alone |
Coyoneda | CoyonedaFunctor, which gives a Functor to a type that has none, as Coyoneda shows |
What builds on Functor
ApplicativeextendsFunctor, andMonadextendsApplicative. Every instance on the next pages has thismap.Traverseextends bothFunctorandFoldable. Foldable and Traverse covers it.Bifunctoris not aFunctor. It maps a type with two parameters, such as both sides of anEither, as Bifunctor shows.
- Applicative: combining independent computations
- Monad: sequencing dependent computations with
flatMap - Bifunctor: mapping over types with two parameters
- One Line, Six Layers: where
mapsits in a whole service method
- Magnus Smith, Functors and Monads with Java and Scala: a practical guide to functors and monads in Java
- Bartosz Milewski, Functors: functors from category theory to code
- Mark Seemann, Functors: a practical introduction, with examples in languages close to Java
Practise Functor mapping in Tutorial 02: Functor Mapping (7 exercises).
Previous: Obtaining Instances Next: Applicative