Foldable & Traverse: Reducing and Reshaping Structures

Fold a container into one value, or run a check on each element and get one result.

"I am a part of all that I have met;"

— Alfred, Lord Tennyson, Ulysses

A fold's result is a part of every element it met: foldMap turns an order's line items into one total.

What You'll Learn

  • Fold any container to one value with foldMap and a monoid
  • Get a total, a check and a list from the same fold, by choosing the monoid and the function that feeds it
  • Run a check on every element with traverse, and get one result for the whole container
  • Predict whether a traversal keeps the first failure or reports them all, from the instance you pass
  • Say when sequenceA fits, and check a Traverse against its identity law

See Example Code

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


Foldable: one structure, many summaries

Summing a list, joining strings and checking that every element passes a test are one walk with three answers. Each answer is a monoid: a way to combine two values, and an empty value to start from. Foldable names the walk, and its one method, foldMap(monoid, f, fa), turns each element of fa into a monoid value with f and combines them. For a List, it is stream().map(f).reduce(monoid.empty(), monoid::combine).

The code on this page uses these imports, with LineItem from the order records the Optics chapter introduces. LINES and lineTotal come from Semigroup and Monoid: LINES holds a lamp at 40.00 and four bulbs at 2.50, and lineTotal multiplies a line's price by its quantity.

import static org.higherkindedj.example.book.foundations.monoid.MonoidBook.LINES;
import static org.higherkindedj.hkt.either.EitherKindHelper.EITHER;
import static org.higherkindedj.hkt.instances.Witnesses.either;
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 static org.higherkindedj.hkt.validated.ValidatedKindHelper.VALIDATED;

import java.math.BigDecimal;
import java.util.List;
import org.higherkindedj.example.book.foundations.monoid.MonoidBook;
import org.higherkindedj.example.book.optics.cast.LineItem;
import org.higherkindedj.hkt.Applicative;
import org.higherkindedj.hkt.Foldable;
import org.higherkindedj.hkt.Kind;
import org.higherkindedj.hkt.Monoids;
import org.higherkindedj.hkt.Semigroups;
import org.higherkindedj.hkt.TypeArity;
import org.higherkindedj.hkt.WitnessArity;
import org.higherkindedj.hkt.effect.ListPath;
import org.higherkindedj.hkt.either.Either;
import org.higherkindedj.hkt.either.EitherKind;
import org.higherkindedj.hkt.instances.Instances;
import org.higherkindedj.hkt.list.ListKind;
import org.higherkindedj.hkt.list.ListTraverse;
import org.higherkindedj.hkt.maybe.Maybe;
import org.higherkindedj.hkt.maybe.MaybeKind;
import org.higherkindedj.hkt.maybe.MaybeTraverse;
import org.higherkindedj.hkt.validated.Validated;
import org.higherkindedj.hkt.validated.ValidatedKind;

On an Effect Path, ListPath, NonDetPath and StreamPath have foldMap themselves, and application code stays there:

    BigDecimal pathTotal =
        ListPath.of(LINES).foldMap(Monoids.bigDecimalAddition(), MonoidBook::lineTotal);
    // 50.00

This page is for a method written once for any container.

Same data, three summaries

    Foldable<ListKind.Witness> foldable = ListTraverse.INSTANCE;
    Kind<ListKind.Witness, LineItem> lines = LIST.widen(LINES);

    BigDecimal sum = foldable.foldMap(Monoids.bigDecimalAddition(), MonoidBook::lineTotal, lines);
    // 50.00

    Boolean everyQuantityPositive =
        foldable.foldMap(Monoids.booleanAnd(), line -> line.quantity() > 0, lines);
    // true

    List<String> skus = foldable.foldMap(Monoids.list(), line -> List.of(line.sku()), lines);
    // [LAMP, BULB]

The three calls differ in the monoid and in the function that feeds it: a line's total for the sum, a test for the check, and a one-element list for the SKUs. ListTraverse.INSTANCE is List's Foldable, and Traverse extends Foldable, so every type with a Traverse can be folded.

One method for any container

total is written over Foldable: it takes the Foldable for F, and calls foldMap with the monoid for BigDecimal addition.

  // One method for any container F: the Foldable passed in walks F, and the monoid adds up
  public static <F extends WitnessArity<TypeArity.Unary>> BigDecimal total(
      Foldable<F> foldable, Kind<F, LineItem> lines) {
    return foldable.foldMap(Monoids.bigDecimalAddition(), MonoidBook::lineTotal, lines);
  }

Run on a List and on a Maybe, it gives:

    BigDecimal orderTotal = total(ListTraverse.INSTANCE, LIST.widen(LINES));
    // 50.00

    BigDecimal oneLine = total(MaybeTraverse.INSTANCE, MAYBE.just(LINES.getFirst()));
    // 40.00

    BigDecimal noLine = total(MaybeTraverse.INSTANCE, MAYBE.nothing());
    // 0

A Maybe holds at most one element, so its total is that line's, and an empty Maybe totals to the monoid's empty value.


Traverse: effectful iteration

Traverse extends Foldable and Functor with traverse(applicative, f, ta). It runs f on every element of ta, where each call returns a value in a second container, such as a Validated, which this page calls an effect. It combines the results with the Applicative you pass, into one effect holding a container of every value: a Kind<T, A> and a function A -> Kind<G, B> give a Kind<G, Kind<T, B>>. Once f has run on each element, the list holds Validateds, and traverse turns it inside out:

Validating every entry in a form, fetching a record for every id or parsing every line of a file all want this. Written by hand, each needs a loop, a list to collect errors and a flag for whether anything failed. traverse is that loop.

Checking every line of an order

An order can ship only when every line asks for at least one unit. The check runs on one line:

  // A check on one line, which fails a line that asks for nothing
  static Validated<List<String>, LineItem> checkLine(LineItem line) {
    return line.quantity() > 0
        ? Validated.valid(line)
        : Validated.invalid(List.of(line.sku() + ": quantity must be positive"));
  }

This order's chair and desk lines ask for nothing:

  /** An order whose chair and desk lines ask for nothing. */
  static final List<LineItem> ZERO_QUANTITIES =
      List.of(
          new LineItem("LAMP", 1, new BigDecimal("40.00")),
          new LineItem("CHAIR", 0, new BigDecimal("60.00")),
          new LineItem("DESK", 0, new BigDecimal("120.00")));

Traversing its lines runs the check on each. The instance decides what a failure does:

    Applicative<ValidatedKind.Witness<List<String>>> validatedApplicative =
        Instances.validated(Semigroups.list());
    Validated<List<String>, List<LineItem>> everyError =
        VALIDATED
            .narrow(
                ListTraverse.INSTANCE.traverse(
                    validatedApplicative,
                    line -> VALIDATED.widen(checkLine(line)),
                    LIST.widen(ZERO_QUANTITIES)))
            .map(LIST::narrow);
    // Invalid([CHAIR: quantity must be positive, DESK: quantity must be positive])

    Applicative<EitherKind.Witness<List<String>>> eitherApplicative =
        Instances.applicative(either());
    Either<List<String>, List<LineItem>> firstError =
        EITHER
            .narrow(
                ListTraverse.INSTANCE.traverse(
                    eitherApplicative,
                    line -> EITHER.widen(checkLine(line).toEither()),
                    LIST.widen(ZERO_QUANTITIES)))
            .map(LIST::narrow);
    // Left([CHAIR: quantity must be positive])

Validated's Applicative joins the errors of every failing line. Either's keeps the first error and drops the rest, though the check still runs on every line. When every line passes, both give the whole list of lines. The Applicative page says what each instance's combining does.

sequenceA

sequenceA is traverse with the identity function, for a container whose elements already are effects. A List of Maybes becomes a Maybe of a List: a Just of every value when each is present, or Nothing when any is missing.

    // Each SKU's price, looked up: the second SKU has none
    List<Kind<MaybeKind.Witness, BigDecimal>> prices =
        List.of(MAYBE.just(new BigDecimal("40.00")), MAYBE.nothing());
    Maybe<List<BigDecimal>> everyPrice =
        MAYBE
            .narrow(
                ListTraverse.INSTANCE.sequenceA(Instances.applicative(maybe()), LIST.widen(prices)))
            .map(LIST::narrow);
    // Nothing

Traverse inside a For comprehension

For has traverse, sequence and flatTraverse steps, so a chain can check every element of a collection without leaving the comprehension. Traversing inside a chain shows them, and ForPath Traverse the same steps on Effect Paths.


The traverse laws

Foldable's one law ties it to Traverse: for a type with both, foldMap gives what traverse gives with Const's applicative. hkj-test does not check it. Traverse keeps three laws.

Laws

  • Identity: traversing with an effect that does nothing changes nothing. traverse with the Id applicative and Id::of gives back ta, wrapped in an Id.
  • Naturality: converting the effect afterwards equals converting each step. For an applicative transformation t, a natural transformation that keeps of and map2, t applied to traverse(f) equals traverse of f followed by t.
  • Composition: two traversals equal one traversal through both effects. Traversing with f and then with g equals one traversal with the two applicatives composed.

Two containers are equal when they hold equal values in the same shape. The identity law pins down the result's shape: it holds every element once, in its place.

TraverseLaws, in hkj-test's org.higherkindedj.hkt.laws package, checks the identity law on any instance. Checking naturality and composition with hkj-test is not supported yet. KindEquivalence.byEqualsAfter, in org.higherkindedj.hkt.assertions, builds the equality from a function it applies to both sides before comparing them with equals. ORDER is any Order, and the test uses these imports, with JUnit's:

import static org.higherkindedj.hkt.list.ListKindHelper.LIST;
import static org.higherkindedj.hkt.maybe.MaybeKindHelper.MAYBE;

import org.higherkindedj.example.book.foundations.monoid.MonoidBook;
import org.higherkindedj.example.book.optics.cast.Order;
import org.higherkindedj.hkt.assertions.KindEquivalence;
import org.higherkindedj.hkt.laws.TraverseLaws;
import org.higherkindedj.hkt.list.ListKind;
import org.higherkindedj.hkt.list.ListTraverse;
import org.higherkindedj.hkt.maybe.MaybeKind;
import org.higherkindedj.hkt.maybe.MaybeTraverse;
  @Test
  @DisplayName("List's and Maybe's Traverse keep the identity law")
  void traverseLaws() {
    TraverseLaws.assertIdentity(
        ListTraverse.INSTANCE,
        LIST.widen(MonoidBook.LINES),
        KindEquivalence.<ListKind.Witness>byEqualsAfter(LIST::narrow));
    TraverseLaws.assertIdentity(
        MaybeTraverse.INSTANCE,
        MAYBE.just(ORDER),
        KindEquivalence.<MaybeKind.Witness>byEqualsAfter(MAYBE::narrow));
    TraverseLaws.assertIdentity(
        MaybeTraverse.INSTANCE,
        MAYBE.<Order>nothing(),
        KindEquivalence.<MaybeKind.Witness>byEqualsAfter(MAYBE::narrow));
  }


Things people get wrong

Common Misunderstandings

  • "Foldable is Stream.reduce with extra steps." It is the same idea, for any container with a Foldable instance: List, Maybe, Either or your own. Stream.reduce works on a Stream, and foldMap on whatever you pass it.
  • "traverse runs its steps at the same time." It runs them in the container's order, and the Applicative decides how their results combine. IO's runs each step after the one before. Validated's joins every error, and Either's keeps the first. For VTasks that run at once, use Par.traverse.
  • "sequenceA and traverse do different things." sequenceA(applicative, ta) is traverse(applicative, x -> x, ta). They differ only in whether there is a function to run on the way.
  • "A Monoid and a Foldable are one type class." They are two. foldMap pairs them: the Foldable walks the container, and the monoid combines what it finds.

See Also

Further Reading

  • Baeldung, Java Stream reduce(): Java's own fold, the idea Foldable generalises
  • Mojang, DataFixerUpper: Minecraft's Java library, which uses traversals to migrate data between game versions

Previous: Semigroup and Monoid Next: Natural Transformation