Applicative, Selective or Monad?

Pick the least powerful of the three that does the job, and keep what that buys.

"It is a capital mistake to theorise before one has data."

— Arthur Conan Doyle, A Scandal in Bohemia

Theorising about a flatMap chain before it runs is Holmes's mistake: its next step is built from data that arrives only when the program runs. An applicative program names every step before any runs, so once it is held as data, you can read it first.

What You'll Learn

  • Choose between Applicative, Selective and Monad by whether a step needs an earlier result
  • Say what each level can express that the one before cannot
  • Hold an applicative program as data, and count or check its instructions before it runs
  • Say why a monadic program cannot be read in advance

See Example Code

The code on this page is AbstractionBook.java, with examples from the Applicative and Monad pages: the page includes them, so the build compiles and runs them. AbstractionBookTest.java holds what the page says. StaticAnalysisExample.java and PermissionCheckingExample.java take the analysis further.


Two questions decide

Ask whether an earlier result decides which effect runs next, and then whether you can name every effect it might choose before the program runs.

flowchart TD
    accTitle: Choosing between Applicative, Selective and Monad
    accDescr: If no earlier result decides which effect runs, use Applicative. If one does, and every effect it might choose can be named up front, use Selective. If the next effect is built from the result, use Monad.
    q1{"Does an earlier result decide<br/>which effect runs next?"}
    q2{"Can you name every effect<br/>it might choose, up front?"}
    app["Applicative<br/><small>map2 to map5</small>"]
    sel["Selective<br/><small>select, whenS, ifS</small>"]
    mon["Monad<br/><small>flatMap</small>"]
    q1 -->|No| app
    q1 -->|Yes| q2
    q2 -->|Yes| sel
    q2 -->|No| mon
    classDef decision fill:#e5c890,stroke:#df8e1d,color:#232634
    classDef domain fill:#a6d189,stroke:#40a02b,color:#232634
    class q1,q2 decision
    class app,sel,mon domain

In words: if results are only combined, as map2 adds two prices, use Applicative. If a result only picks among effects you can name, use Selective. If the next step is built from the result, use Monad. Each level can express what the one before it can, and each step up gives something away. An applicative program held as data can be read before it runs. A selective one names every effect it might run, and a monadic one names only its first.

Applicative: steps that do not depend on one another

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

import static org.higherkindedj.example.book.foundations.OrderOpKindHelper.ORDER_OP;
import static org.higherkindedj.hkt.id.IdKindHelper.ID;

import java.math.BigDecimal;
import java.util.Map;
import java.util.function.Function;
import org.higherkindedj.example.book.foundations.OrderOp;
import org.higherkindedj.example.book.foundations.OrderOpInterpreter;
import org.higherkindedj.example.book.foundations.OrderOpKind;
import org.higherkindedj.example.book.optics.cast.LineItem;
import org.higherkindedj.example.book.optics.cast.Order;
import org.higherkindedj.example.book.optics.cast.OrderLenses;
import org.higherkindedj.example.book.optics.cast.OrderStatus;
import org.higherkindedj.hkt.Applicative;
import org.higherkindedj.hkt.Kind;
import org.higherkindedj.hkt.Monad;
import org.higherkindedj.hkt.TypeArity;
import org.higherkindedj.hkt.WitnessArity;
import org.higherkindedj.hkt.free_ap.FreeAp;
import org.higherkindedj.hkt.free_ap.FreeApAnalyzer;
import org.higherkindedj.hkt.id.Id;
import org.higherkindedj.hkt.id.IdKind;
import org.higherkindedj.hkt.id.IdMonad;

A line item's SKU, quantity and price are checked on their own, so map3 combines them, and no check can change which others run. With Validated's instance, every failing check is reported, as Applicative shows:

  // 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);
  }

Selective: one of a few effects, named up front

A large order is flagged for review, and a small one is not. The flag's effect is passed in before the condition runs, and the condition only decides whether it runs. whenS and ifS work this way, as Selective shows. Every effect that might run is a value you passed in.

Monad: the next step built from the last result

Saving an order needs the order the lookup found, so the save is built from that result, and does not exist until the lookup runs. That is flatMap, as Monad shows:

  // One chain for any container F: save needs the order that was found
  public static <F extends WitnessArity<TypeArity.Unary>> Kind<F, Order> markPaid(
      Monad<F> monad, Kind<F, Order> found, Function<Order, Kind<F, Order>> save) {
    return monad.flatMap(
        order -> save.apply(OrderLenses.status().set(OrderStatus.PAID, order)), found);
  }

Reading a program before it runs

An applicative program can be held as data, so you can check it before anything runs. Count its instructions to estimate the work, look for one that needs a permission, or log what it will do. A Free Applicative holds a program this way. Reading a Selective program before it runs is not supported yet, and a monadic one cannot be read in advance.

The instructions here are the order service's. Each is a record: PriceOf asks for a SKU's price, and Cancel cancels an order. Its k turns the instruction's result into the program's value, so price -> price keeps the price. @EffectAlgebra generates OrderOpKind, ORDER_OP and OrderOpInterpreter from it.

/**
 * The order service's instructions, held as data so that a program built from them can be inspected
 * before an interpreter runs it. {@code @EffectAlgebra} generates the {@code Kind} encoding, the
 * {@code Functor}, the interpreter base class and the {@code Free} constructors.
 */
@NullMarked
@EffectAlgebra
public sealed interface OrderOp<A> permits OrderOp.PriceOf, OrderOp.Cancel {

  /** Maps a function over the result type. */
  <B> OrderOp<B> mapK(Function<? super A, ? extends B> f);

  /**
   * Looks up the price of a SKU.
   *
   * @param sku the SKU to price
   * @param k continuation from the price to {@code A}
   * @param <A> the result type
   */
  record PriceOf<A>(String sku, Function<BigDecimal, A> k) implements OrderOp<A> {
    @Override
    public <B> OrderOp<B> mapK(Function<? super A, ? extends B> f) {
      return new PriceOf<>(sku, k.andThen(f));
    }
  }

  /**
   * Cancels an order.
   *
   * @param orderId the order to cancel
   * @param k continuation from {@link Unit} to {@code A}
   * @param <A> the result type
   */
  record Cancel<A>(UUID orderId, Function<Unit, A> k) implements OrderOp<A> {
    @Override
    public <B> OrderOp<B> mapK(Function<? super A, ? extends B> f) {
      return new Cancel<>(orderId, k.andThen(f));
    }
  }
}

A program prices two SKUs, neither depending on the other, and adds the prices:

  // One instruction, held as data: nothing is priced until an interpreter runs it
  static FreeAp<OrderOpKind.Witness, BigDecimal> priceOf(String sku) {
    return FreeAp.lift(ORDER_OP.widen(new OrderOp.PriceOf<>(sku, price -> price)));
  }

  // Two prices that do not depend on one another, added together
  static final FreeAp<OrderOpKind.Witness, BigDecimal> LAMP_AND_BULB =
      priceOf("LAMP").map2(priceOf("BULB"), BigDecimal::add);

FreeApAnalyzer reads the program without running it:

    int instructions = FreeApAnalyzer.countOperations(LAMP_AND_BULB);
    // 2

    boolean cancels =
        FreeApAnalyzer.containsOperation(
            LAMP_AND_BULB, op -> ORDER_OP.narrow(op) instanceof OrderOp.Cancel<?>);
    // false

An interpreter then decides what each instruction does, and foldMap runs the program with it. Id adds nothing to a value, so the run gives the plain total:

  // Prices from a catalogue: the interpreter decides what each instruction does
  static class CataloguePrices extends OrderOpInterpreter<IdKind.Witness> {
    private final Map<String, BigDecimal> catalogue =
        Map.of("LAMP", new BigDecimal("40.00"), "BULB", new BigDecimal("2.50"));

    @Override
    protected <A> Kind<IdKind.Witness, A> handlePriceOf(OrderOp.PriceOf<A> op) {
      BigDecimal price = catalogue.get(op.sku());
      if (price == null) {
        throw new IllegalArgumentException("no price for " + op.sku());
      }
      return ID.widen(Id.of(op.k().apply(price)));
    }

    @Override
    protected <A> Kind<IdKind.Witness, A> handleCancel(OrderOp.Cancel<A> op) {
      throw new UnsupportedOperationException("a price list cancels nothing");
    }
  }

    BigDecimal total =
        ID.narrow(LAMP_AND_BULB.foldMap(new CataloguePrices(), IdMonad.instance())).value();
    // 42.50

A flatMap chain cannot be read this way: its second step is a function, and what that function does is known only when it runs on the first step's result.

Things people get wrong

Common Misunderstandings

  • "Monad is the safe default." It can do everything, and costs what the others keep. Validated's map3 reports every failing check where its flatMap stops at the first, and a flatMap chain cannot be read before it runs.
  • "An applicative program runs its steps at the same time." No instance on these pages does, as Applicative says.
  • "A Selective program can be analysed before it runs." Only a Free Applicative program can be read first.
  • "Only built-in operations can be read first." Any sealed set of instructions will do, such as OrderOp.

See Also

  • Applicative: combining steps that do not depend on one another
  • Selective: one of a few effects, chosen by an earlier result
  • Monad: chaining steps that depend on the last result
  • Free Applicative: applicative programs held as data

Further Reading


Previous: MonadZero Next: Bifunctor