Selective: Conditional Effects

Run an effect only when an earlier result calls for it, with every branch named up front.

What You'll Learn

  • Apply a function only to a value that still needs it, with select
  • Run an effect only when a condition holds with whenS, and pick one of two with ifS
  • Say what giving every branch up front buys, and where a program can be inspected before it runs
  • Get the Selective instance for each type that has one
  • Check an instance against the two laws hkj-test checks

See Example Code

The code on this page is SelectiveBook.java: the page includes it, so the build compiles and runs it. SelectiveBookTest.java holds what the page says each operation runs, and FoundationsLawsBookTest.java checks the laws.


Between Applicative and Monad

Applicative's map2 combines effects that do not depend on one another: no value one effect gives can decide whether another runs. Monad's flatMap lets a step choose the next effect from the last result, but the next effect does not exist until the step runs. Selective sits between them: an earlier result decides whether an effect runs, and every effect that might run is named up front.

Selective extends Applicative, and every Selective in the library is also a Monad. Applicative, Selective or Monad? walks through choosing among the three for a task. On an Effect Path, a via step with an if does this job for one container.

The code on this page uses these imports:

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

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import org.higherkindedj.hkt.Kind;
import org.higherkindedj.hkt.Selective;
import org.higherkindedj.hkt.Unit;
import org.higherkindedj.hkt.io.IO;
import org.higherkindedj.hkt.io.IOKind;
import org.higherkindedj.hkt.io.IOSelective;
import org.higherkindedj.hkt.maybe.Maybe;
import org.higherkindedj.hkt.maybe.MaybeKind;
import org.higherkindedj.hkt.maybe.MaybeSelective;

Import the library's IO by name: Java 25 has a java.lang.IO too.

select: apply a function only where it is needed

A Choice<A, B> is a Left holding an A or a Right holding a B, and Selective.left and Selective.right build one. Here Left means not done yet, not failure.

select(fab, ff) takes a container of Choice<A, B> and a container of a function from A to B. A Left(a) still needs the function, so select applies it. A Right(b) is already the answer, so select returns it untouched. With ap, a Nothing function would make any result Nothing:

    Selective<MaybeKind.Witness> selective = MaybeSelective.INSTANCE;
    Kind<MaybeKind.Witness, Function<String, BigDecimal>> parse = MAYBE.just(BigDecimal::new);

    // A Left still needs parsing, so select applies the function to it
    Maybe<BigDecimal> parsed =
        MAYBE.narrow(selective.select(MAYBE.just(Selective.left("40.00")), parse));
    // Just(40.00)

    // A Right is ready, so select never needs the function, even a missing one
    Maybe<BigDecimal> ready =
        MAYBE.narrow(
            selective.select(MAYBE.just(Selective.right(new BigDecimal("2.50"))), MAYBE.nothing()));
    // Just(2.50)

whenS: run an effect only when a condition holds

The condition is itself an effect: an IO that, when it runs, says whether an order's total is over 100.00.

  // An order above this total is large: it is reviewed, and it goes by freight
  static final BigDecimal LARGE = new BigDecimal("100.00");

  static Kind<IOKind.Witness, Boolean> isLarge(BigDecimal total) {
    return IO_OP.widen(IO.delay(() -> total.compareTo(LARGE) > 0));
  }

whenS(condition, effect) runs the effect only when the condition gives true, and gives Unit either way. Flagging an order for review runs only for a large one:

  // Flags an order for review, but only when it is large
  static Kind<IOKind.Witness, Unit> reviewIfLarge(BigDecimal total, List<String> flagged) {
    Kind<IOKind.Witness, Unit> flag =
        IO_OP.widen(IO.fromRunnable(() -> flagged.add("review " + total)));
    return IOSelective.INSTANCE.whenS(isLarge(total), flag);
  }

  // Runs the review for each total, and gives what it flagged
  static List<String> reviewAll(List<BigDecimal> totals) {
    List<String> flagged = new ArrayList<>();
    totals.forEach(total -> IO_OP.narrow(reviewIfLarge(total, flagged)).unsafeRunSync());
    return flagged;
  }

Run for an order of 50.00 and one of 120.00, it flags only the second:

    List<String> flagged = reviewAll(List.of(new BigDecimal("50.00"), new BigDecimal("120.00")));
    // [review 120.00]

whenS_ does the same for an effect that gives a value, and drops the value.

ifS: pick one of two effects

ifS(condition, then, else) gives then when the condition gives true and else when it gives false. Both are given up front, and IO's ifS runs the condition, then only the branch it picks. A large order goes by freight, and any other by post:

  // Books freight for a large order and post for any other: only the chosen booking runs
  static Kind<IOKind.Witness, String> bookCourier(BigDecimal total, List<String> booked) {
    Kind<IOKind.Witness, String> freight = book("freight", booked);
    Kind<IOKind.Witness, String> post = book("post", booked);
    return IOSelective.INSTANCE.ifS(isLarge(total), freight, post);
  }

  // Books a courier for the total, and gives every booking made
  static List<String> bookingsFor(BigDecimal total) {
    List<String> booked = new ArrayList<>();
    IO_OP.narrow(bookCourier(total, booked)).unsafeRunSync();
    return booked;
  }

  static Kind<IOKind.Witness, String> book(String courier, List<String> booked) {
    return IO_OP.widen(
        IO.delay(
            () -> {
              booked.add(courier);
              return courier;
            }));
  }

    List<String> booked = bookingsFor(new BigDecimal("50.00"));
    // [post]

A condition that holds more than one answer gives more than one branch. List's ifS gives both branches' results for [true, false]. Validated's gathers both branches' errors when the condition is itself invalid.

Other operations

OperationWhat it does
branch(fab, onLeft, onRight)Applies onLeft to a Left and onRight to a Right, running only the handler it applies
orElse(alternatives)Gives the first Right in a list of Choice containers, or the last Left when none is a Right
apS(initial, steps)Runs each step on the value while it is a Right, and stops at the first Left

This orElse takes Choice containers. The Alternative on the next page has an orElse of its own, a different method.

What "given up front" buys

With flatMap, the next effect is built by a function from the last result, so nothing can see it before the program runs. With Selective, every effect that might run is a value you passed in, so a program held as data could be inspected before it runs. Holding a Selective program as data is not supported yet. A Free Applicative program has no conditions, and FreeApAnalyzer lists every effect it will run.

An instance such as IOSelective or MaybeSelective runs a program, and inspects nothing. None of them runs two branches at the same time.

Laws

The Selective Applicative Functors paper gives select three laws: identity, distributivity and associativity. They do not require a select to skip the function for a Right. Checking them with hkj-test is not supported yet. SelectiveLaws checks two stricter properties, which the library's instances keep.

Laws

  • Left pure: a known Left applies the function. select(of(Left(a)), ff) equals ap(ff, of(a)).
  • Right pure: a known Right skips the function. select(of(Right(b)), ff) equals of(b), even when ff has failed.

Two containers are equal when they hold equal values, or equal errors, in the same shape. The checks assume functions that never return null, and Values, never null says what each type does with one.

SelectiveLaws, in hkj-test's org.higherkindedj.hkt.laws package, checks both 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. The test uses these imports, with JUnit's:

import static org.higherkindedj.hkt.either.EitherKindHelper.EITHER;
import static org.higherkindedj.hkt.maybe.MaybeKindHelper.MAYBE;

import java.math.BigDecimal;
import java.util.function.Function;
import org.higherkindedj.hkt.Kind;
import org.higherkindedj.hkt.Selective;
import org.higherkindedj.hkt.assertions.KindEquivalence;
import org.higherkindedj.hkt.either.Either;
import org.higherkindedj.hkt.either.EitherKind;
import org.higherkindedj.hkt.either.EitherSelective;
import org.higherkindedj.hkt.laws.SelectiveLaws;
import org.higherkindedj.hkt.maybe.MaybeKind;
import org.higherkindedj.hkt.maybe.MaybeSelective;
  @Test
  @DisplayName("Maybe's and Either's Selective keep the two pure laws")
  void selectiveLaws() {
    Kind<MaybeKind.Witness, Function<String, BigDecimal>> parseMaybe = MAYBE.just(BigDecimal::new);
    Kind<EitherKind.Witness<String>, Function<String, BigDecimal>> parseEither =
        EITHER.widen(Either.right(BigDecimal::new));
    Selective<EitherKind.Witness<String>> eitherSelective = EitherSelective.instance();

    SelectiveLaws.assertLeftPure(
        MaybeSelective.INSTANCE,
        "40.00",
        parseMaybe,
        KindEquivalence.<MaybeKind.Witness>byEqualsAfter(MAYBE::narrow));
    // a Right must skip the function, so give it a function that has failed
    SelectiveLaws.assertRightPure(
        MaybeSelective.INSTANCE,
        new BigDecimal("2.50"),
        MAYBE.<Function<String, BigDecimal>>nothing(),
        KindEquivalence.<MaybeKind.Witness>byEqualsAfter(MAYBE::narrow));
    SelectiveLaws.assertLeftPure(
        eitherSelective,
        "40.00",
        parseEither,
        KindEquivalence.<EitherKind.Witness<String>>byEqualsAfter(EITHER::narrow));
    SelectiveLaws.assertRightPure(
        eitherSelective,
        new BigDecimal("2.50"),
        EITHER.<String, Function<String, BigDecimal>>widen(Either.left("no parser")),
        KindEquivalence.<EitherKind.Witness<String>>byEqualsAfter(EITHER::narrow));
  }

Things people get wrong

Common Misunderstandings

  • "A Selective program is analysed before it runs." An instance such as IOSelective runs it, and holding a Selective program as data is not supported yet.
  • "ifS runs both branches." IO's runs the condition and then the chosen branch. Only a condition that holds more than one answer, as a List can, gives both.
  • "Both branches run at the same time." No instance runs them together. For VTasks that run at once, use Par.
  • "whenS needs a Monad." It needs only select, which a Selective provides.

The fine print

Which types have a Selective

TypeInstance
MaybeMaybeSelective.INSTANCE
OptionalOptionalSelective.INSTANCE
ListListSelective.INSTANCE
IOIOSelective.INSTANCE
Either<E, ?>EitherSelective.instance()
Reader<R, ?>ReaderSelective.instance()
IdIdSelective.instance()
Validated<E, ?>ValidatedSelective.instance(semigroup), whose semigroup joins the errors select meets

Instances has no selective factory, so ask the class for its instance.

A Selective of your own

An instance needs select, with of and ap from Applicative and map from Functor. The defaults for whenS, ifS and branch run a guarded effect exactly when your select runs the function's effect. Skip that effect for a Right, as the library's instances do, and the defaults run only the chosen effect. A select built from ap runs every effect.


See Also

Further Reading


Previous: Natural Transformation Next: Alternative