Alternative: Choosing Between Containers

Try one value and fall back to another, with empty for a value that is not there.

What You'll Learn

  • Fall back from one Maybe to another with orElse, building the fallback only when it is needed
  • Predict what orElse does for each instance: fall back for Maybe and Optional, join for List
  • Try any number of sources with orElseAll
  • Turn a test into a value with guard
  • Check an instance against the Alternative laws

See Example Code

The code on this page is AlternativeBook.java: the page includes it, so the build compiles and runs it. AlternativeBookTest.java holds what the page says each instance does, and FoundationsLawsBookTest.java checks the laws.


Trying a fallback

Alternative extends Applicative with two methods. empty() gives a container with nothing in it, and orElse(fa, fb) picks between two containers. fb is a Supplier, so an instance can build the fallback only when it needs it. If you have written optional.or(() -> other), you have used one.

On an Effect Path, MaybePath.orElse falls back in the same way, and application code stays there. This page uses the Kind encoding, which lets one method serve any container.

The code on this page uses these imports:

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 org.higherkindedj.hkt.Alternative;
import org.higherkindedj.hkt.Kind;
import org.higherkindedj.hkt.Unit;
import org.higherkindedj.hkt.instances.Instances;
import org.higherkindedj.hkt.list.ListKind;
import org.higherkindedj.hkt.maybe.Maybe;
import org.higherkindedj.hkt.maybe.MaybeKind;

Instances.alternative(maybe()) gives Maybe's instance. A SKU's price comes from today's offers if there is one, and otherwise from the catalogue:

  static final Alternative<MaybeKind.Witness> MAYBE_ALT = Instances.alternative(maybe());

  // Where a SKU's price can come from: today's offers first, then the catalogue
  static Kind<MaybeKind.Witness, BigDecimal> offerFor(String sku) {
    return sku.equals("BULB") ? MAYBE.just(new BigDecimal("2.00")) : MAYBE.nothing();
  }

  static Kind<MaybeKind.Witness, BigDecimal> catalogueFor(String sku) {
    return sku.equals("CHAIR") ? MAYBE.nothing() : MAYBE.just(new BigDecimal("40.00"));
  }

Maybe's orElse gives the first Just, and asks for the fallback only when the first is Nothing:

    Alternative<MaybeKind.Witness> maybeAlt = MAYBE_ALT;

    Maybe<BigDecimal> lampPrice =
        MAYBE.narrow(maybeAlt.orElse(offerFor("LAMP"), () -> catalogueFor("LAMP")));
    // Just(40.00)

    Maybe<BigDecimal> bulbPrice =
        MAYBE.narrow(maybeAlt.orElse(offerFor("BULB"), () -> catalogueFor("BULB")));
    // Just(2.00)

    Maybe<BigDecimal> chairPrice =
        MAYBE.narrow(maybeAlt.orElse(offerFor("CHAIR"), () -> catalogueFor("CHAIR")));
    // Nothing

One method, two meanings

List's orElse does not fall back: it joins the two lists, and so it always builds the second.

    Alternative<ListKind.Witness> listAlt = Instances.alternative(list());

    List<String> skus =
        LIST.narrow(
            listAlt.orElse(LIST.widen(List.of("LAMP", "BULB")), () -> LIST.widen(List.of("DESK"))));
    // [LAMP, BULB, DESK]
Typeempty()orElse(fa, fb)Instance
MaybeNothingfa if it is a Just, otherwise fbInstances.alternative(maybe())
OptionalOptional.empty()fa if it is present, otherwise fbInstances.alternative(optional())
List[]fa's elements, then fb'sInstances.alternative(list())
StreamAn empty streamfa's elements, then fb's, lazilyInstances.alternative(stream())
VStreamAn empty streamfa's elements, then fb's, lazilyInstances.alternative(vstream())

MaybeMonad, OptionalMonad, ListMonad and StreamMonad are each a MonadZero, which extends both Monad and Alternative.

Many sources

orElseAll(fa, fb, more...) tries any number of sources in order, and stops at the first present value for Maybe. Each source after the first is a Supplier, so a source after that value is never built.

  // The offer, then the catalogue, then a default: the first present price wins
  @SuppressWarnings(
      "unchecked") // varargs orElseAll: Java allows no @SafeVarargs on a default method
  static Kind<MaybeKind.Witness, BigDecimal> priceOrDefault(String sku) {
    return MAYBE_ALT.orElseAll(
        offerFor(sku), () -> catalogueFor(sku), () -> MAYBE.just(new BigDecimal("60.00")));
  }

    Maybe<BigDecimal> chairOrDefault = MAYBE.narrow(priceOrDefault("CHAIR"));
    // Just(60.00)

A call to this form draws javac's unchecked warning for a generic varargs array, since Java allows no @SafeVarargs on an interface's default method. Suppress it on the method that makes the call, as the example does. orElseAll(Iterable) takes a list built at run time, with no warning. Its sources are values, not Suppliers. For Maybe it gives the first present source, and List, Stream and VStream join them all. Every instance but Stream's walks the whole list, so it never ends on an infinite one. Stream's walks only as far as you read the result, so limit(3) ends even on an endless Iterable.

Turning a test into a value

guard(test) gives of(Unit) when the test holds and empty() when it fails. () is how Unit prints:

    // guard turns a test into a value: of(Unit) when it holds, empty when it fails
    BigDecimal total = new BigDecimal("50.00");

    Maybe<Unit> overForty = MAYBE.narrow(maybeAlt.guard(total.compareTo(new BigDecimal("40")) > 0));
    // Just(())

    Maybe<Unit> overHundred =
        MAYBE.narrow(maybeAlt.guard(total.compareTo(new BigDecimal("100")) > 0));
    // Nothing

A monad with a zero can continue from it, so a failed test ends the chain. MonadZero's filter and a For comprehension's when work this way.

Laws

An Alternative keeps five laws. The first three make orElse and empty behave like joining strings and the empty string, and the last two make empty absorb ap.

Laws

  • Left identity: an empty first choice changes nothing. orElse(empty(), () -> fa) equals fa.
  • Right identity: an empty fallback changes nothing. orElse(fa, () -> empty()) equals fa.
  • Associativity: grouping three choices differently changes nothing. orElse(orElse(fa, () -> fb), () -> fc) equals orElse(fa, () -> orElse(fb, () -> fc)). The order of the choices still matters: for List, orElse(fa, () -> fb) and orElse(fb, () -> fa) give the elements in different orders.
  • Left absorption: an empty function gives empty. ap(empty(), fa) equals empty().
  • Right absorption: an empty value gives empty. ap(ff, empty()) equals empty().

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

Checking these laws with hkj-test is not supported yet, so the test checks them by hand, for Maybe and List. It uses these imports, with JUnit's:

import static org.assertj.core.api.Assertions.assertThat;
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.util.List;
import java.util.function.BiPredicate;
import java.util.function.Function;
import org.higherkindedj.hkt.Alternative;
import org.higherkindedj.hkt.Kind;
import org.higherkindedj.hkt.TypeArity;
import org.higherkindedj.hkt.WitnessArity;
import org.higherkindedj.hkt.assertions.KindEquivalence;
import org.higherkindedj.hkt.instances.Instances;
import org.higherkindedj.hkt.list.ListKind;
import org.higherkindedj.hkt.maybe.MaybeKind;
  <F extends WitnessArity<TypeArity.Unary>, A> void assertAlternativeLaws(
      Alternative<F> alt,
      Kind<F, A> fa,
      Kind<F, A> fb,
      Kind<F, A> fc,
      Kind<F, Function<A, A>> ff,
      BiPredicate<Kind<F, ?>, Kind<F, ?>> same) {
    // empty changes nothing, on either side
    assertThat(same.test(alt.orElse(alt.empty(), () -> fa), fa)).isTrue();
    assertThat(same.test(alt.orElse(fa, alt::empty), fa)).isTrue();
    // grouping the choices differently changes nothing
    assertThat(
            same.test(
                alt.orElse(alt.orElse(fa, () -> fb), () -> fc),
                alt.orElse(fa, () -> alt.orElse(fb, () -> fc))))
        .isTrue();
    // an empty function, or an empty value, makes ap empty
    assertThat(same.test(alt.ap(alt.<Function<A, A>>empty(), fa), alt.empty())).isTrue();
    assertThat(same.test(alt.ap(ff, alt.<A>empty()), alt.empty())).isTrue();
  }

  @Test
  @DisplayName("Maybe's and List's Alternative keep identity, associativity and absorption")
  void alternativeLaws() {
    Alternative<MaybeKind.Witness> maybeAlt = Instances.alternative(maybe());
    Alternative<ListKind.Witness> listAlt = Instances.alternative(list());
    Function<String, String> lower = String::toLowerCase;

    for (Kind<MaybeKind.Witness, String> fa :
        List.of(MAYBE.just("LAMP"), MAYBE.<String>nothing())) {
      assertAlternativeLaws(
          maybeAlt,
          fa,
          MAYBE.just("BULB"),
          MAYBE.just("DESK"),
          MAYBE.just(lower),
          KindEquivalence.<MaybeKind.Witness>byEqualsAfter(MAYBE::narrow));
    }
    assertAlternativeLaws(
        listAlt,
        LIST.widen(List.of("LAMP", "BULB")),
        LIST.widen(List.of("DESK")),
        LIST.widen(List.<String>of()),
        LIST.widen(List.of(lower)),
        KindEquivalence.<ListKind.Witness>byEqualsAfter(LIST::narrow));
  }

Things people get wrong

Common Misunderstandings

  • "orElse always falls back." Maybe's and Optional's do. List's, Stream's and VStream's join both containers.
  • "orElse picks whichever value is present." It prefers the first. Two present prices give the offer, not the catalogue's.
  • "Every type with a Monad has an Alternative." Only Maybe, Optional, List, Stream and VStream have one. Instances.alternative(either()) compiles, and throws ClassCastException when it runs, as what the compiler checks explains.
  • "This orElse is Selective's." Selective's orElse takes a list of Choice containers, and is a different method.

See Also

Further Reading


Previous: Selective Next: MonadZero