MonadZero: Filtering in Monadic Chains
Give a monad an empty value, and a chain can drop whatever fails a test.
- Say what a
zeroadds to aMonad, and why a chain ends at one - Drop a value that fails a test with
filter, in a method written once for any container - Guard a step of a
Forcomprehension withwhen - Name the types that have a zero, and what each one's is
- Check an instance against the two zero laws
The code on this page is MonadZeroBook.java: the page includes it, so the build compiles and runs it. MonadZeroBookTest.java holds what the page says each instance does, and FoundationsLawsBookTest.java checks the laws.
A monad with an empty value
MonadZero extends Monad and Alternative, and adds zero(): a container with nothing in it, which is also its Alternative's empty(). A flatMap over a zero has no value to run its step on, so the chain ends there. For a List, each element runs the rest of the chain on its own, so a zero ends only that element's run. That is enough to filter: replace a value that fails a test with a zero. If you have called stream.filter or optional.filter, you have done this for one container.
On an Effect Path, MaybePath.filter does it for a Maybe, and application code stays there. This page is for a method written once for any container. Its code uses these imports, with LineItem from the order records the Optics chapter introduces:
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.example.book.optics.cast.LineItem;
import org.higherkindedj.hkt.Kind;
import org.higherkindedj.hkt.MonadZero;
import org.higherkindedj.hkt.TypeArity;
import org.higherkindedj.hkt.WitnessArity;
import org.higherkindedj.hkt.expression.For;
import org.higherkindedj.hkt.instances.Instances;
import org.higherkindedj.hkt.list.ListKind;
import org.higherkindedj.hkt.maybe.Maybe;
import org.higherkindedj.hkt.maybe.MaybeKind;
The examples use two baskets:
// Two baskets: a lamp and four bulbs, then three more bulbs
static final LineItem LAMP = new LineItem("LAMP", 1, new BigDecimal("40.00"));
static final List<List<LineItem>> BASKETS =
List.of(
List.of(LAMP, new LineItem("BULB", 4, new BigDecimal("2.50"))),
List.of(new LineItem("BULB", 3, new BigDecimal("2.50"))));
Filtering with filter
filter(predicate, ma) keeps a value that passes and gives a zero for one that fails: it is flatMap(a -> predicate.test(a) ? of(a) : zero(), ma), with the arguments in flatMap's order, the test first. Written once over MonadZero, one method filters any container that has a zero:
// One method for any container with a zero: keeps a line only when it asks for more than one
public static <F extends WitnessArity<TypeArity.Unary>> Kind<F, LineItem> bulk(
MonadZero<F> monadZero, Kind<F, LineItem> lines) {
return monadZero.filter(line -> line.quantity() > 1, lines);
}
MonadZero<ListKind.Witness> listZero = Instances.monadZero(list());
MonadZero<MaybeKind.Witness> maybeZero = Instances.monadZero(maybe());
List<LineItem> bulkLines = LIST.narrow(bulk(listZero, LIST.widen(BASKETS.getFirst())));
// [LineItem[sku=BULB, quantity=4, price=2.50]]
Maybe<LineItem> bulkLamp = MAYBE.narrow(bulk(maybeZero, MAYBE.just(LAMP)));
// Nothing
Each type's zero is what a failed test leaves:
| Type | zero() | A failed test |
|---|---|---|
List | [] | Drops that element from the list |
Maybe | Nothing | Ends the chain at Nothing |
Optional | Optional.empty() | Ends the chain at an empty Optional |
Stream | An empty stream | Drops that element, lazily |
Instances.monadZero(token) gives the instance for list(), maybe(), optional() and stream(), and for any other token fails when it runs, as what the compiler checks explains.
Guarding a For comprehension with when
A For comprehension given a MonadZero, as in For.from(monadZero, ...), has a when(test) step, and so do For.par and ForState.withState given one. When the test fails for a combination, that combination gives a zero, and the comprehension drops it. The test sees what the comprehension holds so far: one value as itself, two or more as a tuple, and in ForState the state. Here it holds a basket and a line, so t._2() is the line, and when keeps only the lines that ask for more than one unit:
List<String> bulkSkus =
LIST.narrow(
For.from(listZero, LIST.widen(BASKETS))
.from(basket -> LIST.widen(basket))
.when(t -> t._2().quantity() > 1)
.yield((basket, line) -> line.sku() + " x" + line.quantity()));
// [BULB x4, BULB x3]
A comprehension started with a plain Monad has no when, and javac says so:
For.from(Instances.monad(list()), LIST.widen(List.of(1, 2, 3)))
.when(n -> n > 1)
.yield(n -> n);
javac refuses it with "cannot find symbol", naming when. For Comprehension shows when in a longer chain.
Two laws
A MonadZero keeps two laws beyond the Monad and Alternative ones. Together they say a zero ends a chain whichever end it is at.
- Left zero: no step runs after a zero.
flatMap(f, zero())equalszero(). - Right zero: a step that gives a zero makes the chain a zero.
flatMap(a -> zero(), fa)equalszero().
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. ORDER is any Order, and the test 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.example.book.optics.cast.Order;
import org.higherkindedj.hkt.Kind;
import org.higherkindedj.hkt.MonadZero;
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, B> void assertMonadZeroLaws(
MonadZero<F> monadZero,
Kind<F, A> fa,
Function<A, Kind<F, B>> f,
BiPredicate<Kind<F, ?>, Kind<F, ?>> same) {
// a zero ends the chain: no step after it runs
assertThat(same.test(monadZero.flatMap(f, monadZero.<A>zero()), monadZero.zero())).isTrue();
// a step that gives zero makes the chain zero
assertThat(same.test(monadZero.flatMap(a -> monadZero.<B>zero(), fa), monadZero.zero()))
.isTrue();
}
@Test
@DisplayName("Maybe's and List's MonadZero keep the zero laws")
void monadZeroLaws() {
MonadZero<MaybeKind.Witness> maybeZero = Instances.monadZero(maybe());
MonadZero<ListKind.Witness> listZero = Instances.monadZero(list());
assertMonadZeroLaws(
maybeZero,
MAYBE.just(ORDER),
order -> MAYBE.just(order.customer()),
KindEquivalence.<MaybeKind.Witness>byEqualsAfter(MAYBE::narrow));
assertMonadZeroLaws(
listZero,
LIST.widen(List.of(ORDER, ORDER)),
order -> LIST.widen(order.lines()),
KindEquivalence.<ListKind.Witness>byEqualsAfter(LIST::narrow));
}
Things people get wrong
- "Filtering needs a
Forcomprehension."filter(predicate, ma)filters directly, asbulkdoes. - "
whenworks with anyMonad." Only a comprehension given aMonadZerohas it. - "A filtered
Maybekeeps the value it failed on." It givesNothing, and the value is gone, as it is fromoptional.filter. - "
Eitherhas a zero."Eitherhas no empty value to give, since aLeftmust hold an error.Instances.monadZero(either())compiles, and throwsClassCastExceptionwhen it runs.
- Alternative:
emptyandorElse, which everyMonadZerohas - For Comprehension:
whenamong the other comprehension steps
Previous: Alternative Next: Applicative, Selective or Monad?