Applicative: Combining Independent Computations
Combine values that do not depend on one another, and let each container's instance decide what a failure does.
"The acts of the mind, wherein it exerts its power over its simple ideas, are chiefly these three: (1) Combining several simple ideas into one compound one; and thus all complex ideas are made."
— John Locke, An Essay Concerning Human Understanding (Book II, Chapter XII)
map3 performs Locke's first act: it combines three checked values into one line item.
- Build one value from several independent ones with
map2tomap5 - Say what
ofandapadd toFunctor - Predict what each instance's
map2does: combine the errors, keep the first, or give every combination - Choose between
map3andflatMapby whether a step needs another's result - Check an instance against the four applicative laws with
hkj-test'sApplicativeLaws
The code on this page is ApplicativeBook.java: the page includes it, so the build compiles and runs it. ApplicativeBookTest.java holds what the page says each instance does, and FoundationsLawsBookTest.java checks the laws.
When map is not enough
Functor's map changes the value inside one container, and cannot reach a second. A line item needs three values: a SKU, a quantity and a price, each checked on its own. None of the checks needs another's result, so a line item that fails two checks could report both.
For one container, an Effect Path combines values with zipWith, and ValidationPath's zipWithAccum keeps every error, as Error Accumulation shows. ListPath's zipWith pairs by position, where List's Applicative and NonDetPath give every combination. Application code stays on the Paths. This page is for a method written once for any container.
The code on this page uses these imports, with LineItem from the order records the Optics chapter introduces:
import static org.higherkindedj.hkt.either.EitherKindHelper.EITHER;
import static org.higherkindedj.hkt.instances.Witnesses.either;
import static org.higherkindedj.hkt.validated.ValidatedKindHelper.VALIDATED;
import java.math.BigDecimal;
import java.util.List;
import org.higherkindedj.example.book.optics.cast.LineItem;
import org.higherkindedj.hkt.Applicative;
import org.higherkindedj.hkt.Kind;
import org.higherkindedj.hkt.Semigroups;
import org.higherkindedj.hkt.TypeArity;
import org.higherkindedj.hkt.WitnessArity;
import org.higherkindedj.hkt.either.Either;
import org.higherkindedj.hkt.either.EitherKind;
import org.higherkindedj.hkt.instances.Instances;
import org.higherkindedj.hkt.validated.Validated;
import org.higherkindedj.hkt.validated.ValidatedKind;
Each check returns a Validated: a Valid holding the value, or an Invalid holding a list of errors.
// Three checks, each on one field, and none needs another's result
static Validated<List<String>, String> checkSku(String sku) {
return sku.isBlank() ? Validated.invalid(List.of("SKU is blank")) : Validated.valid(sku);
}
static Validated<List<String>, Integer> checkQuantity(int quantity) {
return quantity > 0
? Validated.valid(quantity)
: Validated.invalid(List.of("quantity must be positive"));
}
static Validated<List<String>, BigDecimal> checkPrice(BigDecimal price) {
return price.signum() >= 0
? Validated.valid(price)
: Validated.invalid(List.of("price is negative"));
}
What an Applicative adds
Applicative<F> extends Functor<F> with two methods, and builds map2 to map5 from map and ap:
public interface Applicative<F extends WitnessArity<TypeArity.Unary>> extends Functor<F> {
<A> Kind<F, A> of(@Nullable A value);
<A, B> Kind<F, B> ap(Kind<F, ? extends Function<A, B>> ff, Kind<F, A> fa);
// abridged: the null checks and a curried overload are left out,
// and map3, map4 and map5 follow the same pattern
default <A, B, C> Kind<F, C> map2(
Kind<F, A> fa, Kind<F, B> fb, BiFunction<? super A, ? super B, ? extends C> f) {
return ap(map(a -> b -> f.apply(a, b), fa), fb);
}
}
of lifts a plain value into the container: Validated's gives a Valid, and Maybe's a Just. ap applies a function held in a container to a value held in another.
You will rarely call ap yourself. map(a -> b -> f.apply(a, b), fa) gives a Kind<F, Function<B, C>>: the first value inside a function that waits for the second. ap applies that function to fb. map3 to map5 add an input each the same way, and they are what you call.
One method for any container
lineItem is written over Applicative. It takes the Applicative for F and calls map3 on it:
// One method for any container F: the Applicative passed in decides what a failure does
public static <F extends WitnessArity<TypeArity.Unary>> Kind<F, LineItem> lineItem(
Applicative<F> applicative,
Kind<F, String> sku,
Kind<F, Integer> quantity,
Kind<F, BigDecimal> price) {
return applicative.map3(sku, quantity, price, LineItem::new);
}
Run it with Validated's Applicative, then with Either's, on a blank SKU and a quantity of zero:
Applicative<ValidatedKind.Witness<List<String>>> validatedApplicative =
Instances.validated(Semigroups.list());
Validated<List<String>, LineItem> everyError =
VALIDATED.narrow(
lineItem(
validatedApplicative,
VALIDATED.widen(checkSku(" ")),
VALIDATED.widen(checkQuantity(0)),
VALIDATED.widen(checkPrice(new BigDecimal("40.00")))));
// Invalid([SKU is blank, quantity must be positive])
Applicative<EitherKind.Witness<List<String>>> eitherApplicative =
Instances.applicative(either());
Either<List<String>, LineItem> firstError =
EITHER.narrow(
lineItem(
eitherApplicative,
EITHER.widen(checkSku(" ").toEither()),
EITHER.widen(checkQuantity(0).toEither()),
EITHER.widen(checkPrice(new BigDecimal("40.00")).toEither())));
// Left([SKU is blank])
The call is the same both times. Instances.validated builds Validated's instance from a semigroup, here one that joins two lists, so it reports both errors. With Semigroups.first() it would report only the first. Either's instance always keeps the first. toEither() turns each check's Validated into an Either holding the same errors, so only the instance differs.
What each instance does
Applicative promises that map3 combines the three values when all are there. What it does otherwise is each instance's own:
flowchart LR
accTitle: The instance decides what map3 gives
accDescr: Three independent checks, of the SKU, the quantity and the price, each feed map3. With Validated's Applicative and a semigroup that joins lists, map3 gives every error the checks found. With Either's, it gives only the first.
S["checkSku"] --> M["map3"]
Q["checkQuantity"] --> M
P["checkPrice"] --> M
M -->|"Validated's instance"| V["Invalid: every error"]
M -->|"Either's instance"| E["Left: the first error"]
classDef step fill:#8caaee,stroke:#1e66f5,color:#232634
classDef error fill:#e78284,stroke:#d20f39,color:#232634
class S,Q,P,M step
class V,E error
The diagram shows three checks that never see one another's results, meeting only at map3, where the instance decides what comes out. With two inputs, the instances you will meet most behave like this, and map3 to map5 do the same with more:
| Instance | What map2 does with its two inputs |
|---|---|
Validated, from Instances.validated(semigroup) | Gives the combined value if both are valid; otherwise the invalid inputs' errors, combined by the semigroup in the order of the inputs. Semigroups.list() keeps every error |
Either, Try | Gives the first failure, and drops the second |
Maybe, Optional | Is empty if either input is empty |
List, NonEmptyList | Gives every combination: two lists of two give four values |
IO, VTask | Builds a new deferred value that, when it runs, runs the first input and then the second. If the first fails, the second never runs |
CompletableFuture | Completes when both inputs have. map2 starts neither future, so whether their work overlaps depends on what completes each one |
Writer, from Instances.writer(monoid) | Gives the combined value, with both logs joined by the monoid |
So Applicative promises neither that errors accumulate nor that inputs run at the same time. Its promise is smaller: the inputs do not depend on one another. An instance can use that, as Validated's does, or not, as Either's does. To run two VTasks at the same time, use Par.map2.
Should you use map3 or flatMap?
- Use
flatMapwhen a step needs the previous result. Finding an order's customer needs the order first.flatMapis Monad's. On a failure that holds no value, such as aLeft, it stops, because the next step has nothing to run on. - Use
map2tomap5when the steps are independent. The instance can then do more with the failures, asValidated's does.
The two can differ on one instance. Instances.validated returns a single instance with both methods: its map3 combines the errors of every invalid input, and its flatMap stops at the first. Applicative, Selective or Monad? walks through the choice.
Four laws
An Applicative keeps four laws. Together they say that of adds nothing of its own, and that ap gives the same result however you group the calls.
- Identity: applying a lifted
a -> achanges nothing.ap(of(a -> a), fa)equalsfa. - Homomorphism: a lifted function on a lifted value lifts the result.
ap(of(f), of(x))equalsof(f.apply(x)). - Interchange: lifting the value instead of the function changes nothing.
ap(ff, of(x))equalsap(of(f -> f.apply(x)), ff). - Composition: grouping the applications differently changes nothing.
ap(ap(ap(of(compose), u), v), w)equalsap(u, ap(v, w)), wherecomposeisf -> g -> x -> f.apply(g.apply(x)).
Two containers are equal when they hold equal values, or equal errors, in the same shape. For a deferred container such as IO, they are equal when running both gives equal results. The laws assume functions that never return null, and Values, never null says what each type does with one.
ApplicativeLaws, beside FunctorLaws in hkj-test's org.higherkindedj.hkt.laws package, checks each law on any instance. KindEquivalence.byEqualsAfter, in org.higherkindedj.hkt.assertions, builds the equality from a function it applies to both sides before comparing them with equals. Here VALIDATED::narrow unwraps the Kind. Two IOs that give the same result are different objects, so for IO the function must also run it, as Functor's laws test does. The test checks Validated's instance twice, once with every value valid and once with every value invalid. In the invalid case, Composition must join the three errors in the same order on both sides. ORDER is any Order, and the test uses these imports, with JUnit's:
import static org.higherkindedj.hkt.validated.ValidatedKindHelper.VALIDATED;
import java.util.List;
import java.util.function.Function;
import org.higherkindedj.example.book.optics.cast.Customer;
import org.higherkindedj.example.book.optics.cast.EmailAddress;
import org.higherkindedj.example.book.optics.cast.Order;
import org.higherkindedj.hkt.Applicative;
import org.higherkindedj.hkt.Semigroups;
import org.higherkindedj.hkt.assertions.KindEquivalence;
import org.higherkindedj.hkt.instances.Instances;
import org.higherkindedj.hkt.laws.ApplicativeLaws;
import org.higherkindedj.hkt.validated.Validated;
import org.higherkindedj.hkt.validated.ValidatedKind;
void assertApplicativeLaws(
Validated<List<String>, Order> order,
Validated<List<String>, Function<Order, Customer>> customer,
Validated<List<String>, Function<Customer, EmailAddress>> email) {
Applicative<ValidatedKind.Witness<List<String>>> applicative =
Instances.validated(Semigroups.list());
var same =
KindEquivalence.<ValidatedKind.Witness<List<String>>>byEqualsAfter(VALIDATED::narrow);
ApplicativeLaws.assertIdentity(applicative, VALIDATED.widen(order), same);
ApplicativeLaws.assertHomomorphism(applicative, ORDER, Order::customer, same);
ApplicativeLaws.assertInterchange(applicative, VALIDATED.widen(customer), ORDER, same);
ApplicativeLaws.assertComposition(
applicative,
VALIDATED.widen(email),
VALIDATED.widen(customer),
VALIDATED.widen(order),
same);
}
@Test
@DisplayName("Validated's Applicative keeps all four laws when every value is Valid")
void validatedApplicativeLawsWhenValid() {
assertApplicativeLaws(
Validated.valid(ORDER), Validated.valid(Order::customer), Validated.valid(Customer::email));
}
@Test
@DisplayName("Validated's Applicative keeps all four laws when every value is Invalid")
void validatedApplicativeLawsWhenInvalid() {
assertApplicativeLaws(
Validated.invalid(List.of("order not found")),
Validated.invalid(List.of("no customer")),
Validated.invalid(List.of("no email")));
}
Things people get wrong
- "
Applicativeaccumulates errors."Validated's instance does.Either's keeps the first error, and both areApplicatives. - "
Applicativeruns its inputs at the same time." No instance on this page starts its inputs together:IOandVTaskrun them in order, andCompletableFuture's waits for two futures it never started. ForVTasks that run at once, usePar.map2. - "
ApplicativeisMonadwithoutflatMap." EveryMonadhas anap, but an instance'sapcan do what itsflatMapcannot, asValidated's does. - "
map2is only for two values."map3,map4andmap5take more, and stop at five. For a record with more fields,Validated.fields()in Accumulating Assembly takes more.
You can now build one value from several independent ones, in a method written once for any container, as lineItem is. You can say what each instance does with a failure, and check an instance against the four laws. The rest of this page is for which types have an Applicative, where Validated bends a rule, and what builds on Applicative.
With List's instance, what does map2 give for the SKUs ["LAMP", "DESK"] and an empty list of quantities?
Answer and why
Answer and why
An empty list. List's map2 gives every combination of the two inputs, and two SKUs with no quantities make no combinations.
Where this lives: What each instance does.
Two VTasks each take a second to run. About how long does running Instances.applicative(vtask()).map2(first, second, f) take, and what would take one second?
Answer and why
Answer and why
About two seconds. VTask's map2 runs the first task, then the second. Par.map2 runs the two at the same time, so it takes about one.
Where this lives: What each instance does.
The fine print
Which types have an Applicative
| Types | Their Applicative comes from |
|---|---|
Every token in Witnesses | Their Monad, so Instances.applicative(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 and Coyoneda | Nowhere: they have a Functor only |
Where Validated bends a rule
A Monad's ap should agree with its flatMap: ap(ff, fa) should equal flatMap(f -> map(f, fa), ff). Validated's instance breaks this on purpose, as its javadoc says, so that map2 to map5 can combine the errors of every input. hkj-test's MonadLaws checks the three monad laws, not this one. Validated says when you want each behaviour. Laws and Where HKJ Bends Them lists the other instances that bend a law.
What builds on Applicative
MonadextendsApplicative. Every monad on the next pages hasof,apandmap2.SelectiveandAlternativeextend it too. Selective adds steps that run only when a condition holds, and Alternative adds a fallback.Traversetakes anApplicative.traverseruns a function on every element and combines the results with the instance it is given, soValidated's combines every element's errors, as Foldable and Traverse shows.
- Functor: the
mapthatApplicativeextends - Monad: sequencing dependent computations with
flatMap - Applicative, Selective or Monad?: choosing by whether a step needs an earlier result
- Validated: the type built to report every error
- Conor McBride and Ross Paterson, Applicative Programming with Effects: the paper that introduced applicative functors
- Mark Seemann, Applicative Functors: a practical introduction, with examples in languages close to Java
Practise Applicative combining in Tutorial 03: Applicative Combining (8 exercises).