EitherF: Composing Effect Vocabularies
One program, two instruction sets, and each instruction sent to the interpreter for its own set.
"Only connect! That was the whole of her sermon."
— E. M. Forster, Howards End (Chapter XXII)
Margaret Schlegel's sermon is meant for Henry Wilcox, who keeps the two halves of his life apart. Two instruction sets kept apart cannot share a program either. EitherF connects them: one program uses both, and each instruction still reaches the interpreter for its own set.
| Models | One instruction from either of two instruction sets |
| Replaces | One interface grown to hold every service's operations, or a dispatcher written by hand |
| Effect Path | None: a program over the pair is a FreePath |
| Instances | Functor |
| Choose it when | One program needs instructions from two or more sets, which @ComposeEffects joins for you; otherwise Free over one set, or compare every type in Choosing a Type |
- Join two instruction sets so that one program can use both
- Run the program with an interpreter for each set, combined into one
- Read what
@ComposeEffectsgenerates: anInjectfor each set and the pair'sFunctor - Move a program written for one set into the pair without changing it
- Nest a third and a fourth instruction set
The code on this page is EitherFBook.java, with OrderEffects.java: the page includes them, so the build compiles and runs them. EitherFBookTest.java holds what the page says each method does.
For most code, EitherF is an implementation detail. @ComposeEffects generates what joins the sets, and the Payment Processing example composes four of them. Knowing what that code is made of helps when you read a type error, or join sets by hand.
Two instruction sets, one program
The order service's Free program prices a line and cancels the order when the line costs too much. Now it must also tell the customer why. Notices are a concern of their own, with their own interpreter: an outbox in a test, a mail service when the service runs. They are a second instruction set beside OrderOp:
/**
* The order service's notices to customers, held as data beside {@link OrderOp}, so that one
* program can use both instruction sets. {@code @EffectAlgebra} generates the {@code Kind}
* encoding, the {@code Functor}, the interpreter base class and the {@code Free} constructors.
*/
@NullMarked
@EffectAlgebra
public sealed interface NoticeOp<A> permits NoticeOp.Send {
/** Maps a function over the result type. */
<B> NoticeOp<B> mapK(Function<? super A, ? extends B> f);
/**
* Sends the customer who placed an order a notice about it.
*
* @param orderId the order the notice is about
* @param text what the notice says
* @param k continuation from {@link Unit} to {@code A}
* @param <A> the result type
*/
record Send<A>(UUID orderId, String text, Function<Unit, A> k) implements NoticeOp<A> {
@Override
public <B> NoticeOp<B> mapK(Function<? super A, ? extends B> f) {
return new Send<>(orderId, text, k.andThen(f));
}
}
}
A Free<OrderOpKind.Witness, A> holds OrderOp instructions only, and a program over NoticeOp has another type, so via cannot chain one onto the other. Adding a Send record to OrderOp would mix the two concerns, and every OrderOp interpreter would have to handle notices. The code on this page uses these imports:
import static org.higherkindedj.example.book.foundations.NoticeOpKindHelper.NOTICE_OP;
import static org.higherkindedj.hkt.eitherf.EitherFKindHelper.EITHERF;
import static org.higherkindedj.hkt.id.IdKindHelper.ID;
import static org.higherkindedj.hkt.instances.Witnesses.id;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
import org.higherkindedj.example.book.foundations.NoticeOp;
import org.higherkindedj.example.book.foundations.NoticeOpFunctor;
import org.higherkindedj.example.book.foundations.NoticeOpInterpreter;
import org.higherkindedj.example.book.foundations.NoticeOpKind;
import org.higherkindedj.example.book.foundations.NoticeOpOps;
import org.higherkindedj.example.book.foundations.OrderOp;
import org.higherkindedj.example.book.foundations.OrderOpFunctor;
import org.higherkindedj.example.book.foundations.OrderOpInterpreter;
import org.higherkindedj.example.book.foundations.OrderOpKind;
import org.higherkindedj.example.book.foundations.OrderOpOps;
import org.higherkindedj.hkt.Kind;
import org.higherkindedj.hkt.Natural;
import org.higherkindedj.hkt.Unit;
import org.higherkindedj.hkt.effect.FreePath;
import org.higherkindedj.hkt.effect.Path;
import org.higherkindedj.hkt.eitherf.EitherF;
import org.higherkindedj.hkt.eitherf.EitherFFunctor;
import org.higherkindedj.hkt.eitherf.EitherFKind;
import org.higherkindedj.hkt.eitherf.Interpreters;
import org.higherkindedj.hkt.free.Free;
import org.higherkindedj.hkt.id.Id;
import org.higherkindedj.hkt.id.IdKind;
import org.higherkindedj.hkt.inject.Inject;
import org.higherkindedj.hkt.inject.InjectInstances;
import org.higherkindedj.hkt.instances.Instances;
An instruction from either set
Either<L, R> holds a value that is an L or an R. EitherF<F, G, A> holds an instruction that is from the set F or the set G, each giving an A: Left wraps an instruction from F, and Right one from G. The F in the name says it holds a type constructor's value, as Kind<F, A> does. A program over the pair holds instructions from both sets, and running it sends each to the interpreter for its side:
flowchart TB
accTitle: How one interpreter for the pair dispatches an instruction
accDescr: An instruction in the pair is an EitherF. A Left holds an OrderOp instruction, which goes to the InMemoryOrders interpreter. A Right holds a NoticeOp instruction, which goes to the Outbox interpreter.
I["an instruction in the pair"]:::domain --> D{"Left or Right?"}:::decision
D -->|Left| O["an OrderOp instruction"]:::domain
D -->|Right| N["a NoticeOp instruction"]:::domain
O --> IO["InMemoryOrders"]:::step
N --> OB["Outbox"]:::step
classDef domain fill:#a6d189,stroke:#40a02b,color:#232634
classDef step fill:#8caaee,stroke:#1e66f5,color:#232634
classDef decision fill:#e5c890,stroke:#df8e1d,color:#232634
Joining the sets
@ComposeEffects on a record that names the sets generates what the pair needs:
/**
* The order service's two instruction sets as one. {@code @ComposeEffects} generates {@code
* OrderEffectsSupport}, with an {@code Inject} for each set, the pair's {@code Functor} and a
* {@code BoundSet} to hold each set's constructors.
*/
@NullMarked
@ComposeEffects
public record OrderEffects(Class<OrderOp<?>> orders, Class<NoticeOp<?>> notices) {}
The generated OrderEffectsSupport, in the record's own package, wires the pair. Its functor gives the pair's Functor, which Free needs, and its injectOrders and injectNotices say which side each set takes. Each set's own @EffectAlgebra generates a boundTo, which gives that set's constructors bound to its side. The pair's witness is EitherFKind.Witness<OrderOpKind.Witness, NoticeOpKind.Witness>:
// The pair's Functor maps an instruction from either set
static final EitherFFunctor<OrderOpKind.Witness, NoticeOpKind.Witness> ORDERS_AND_NOTICES =
OrderEffectsSupport.functor(OrderOpFunctor.instance(), NoticeOpFunctor.instance());
// Each set's generated constructors, bound to its side of the pair
static final OrderOpOps.Bound<EitherFKind.Witness<OrderOpKind.Witness, NoticeOpKind.Witness>>
ORDERS = OrderOpOps.boundTo(OrderEffectsSupport.injectOrders(), ORDERS_AND_NOTICES);
static final NoticeOpOps.Bound<EitherFKind.Witness<OrderOpKind.Witness, NoticeOpKind.Witness>>
NOTICES = NoticeOpOps.boundTo(OrderEffectsSupport.injectNotices(), ORDERS_AND_NOTICES);
ORDERS.priceOf and NOTICES.send give Free programs over the pair, so via chains them. The program cancels the order and tells the customer, or does neither:
// Cancels the order if the line costs more than the limit, and tells the customer why
static FreePath<EitherFKind.Witness<OrderOpKind.Witness, NoticeOpKind.Witness>, Boolean>
cancelAndTell(UUID orderId, String sku, BigDecimal limit) {
return Path.free(ORDERS.priceOf(sku, Function.identity()), ORDERS_AND_NOTICES)
.via(
price ->
price.compareTo(limit) <= 0
? Path.freePure(false, ORDERS_AND_NOTICES)
: Path.free(ORDERS.cancel(orderId, Function.identity()), ORDERS_AND_NOTICES)
.then(
() ->
Path.free(
NOTICES.send(
orderId,
"Cancelled: " + sku + " costs " + price,
Function.identity()),
ORDERS_AND_NOTICES))
.map(_ -> true));
}
One interpreter for the pair
Each set keeps an interpreter of its own, written as on the Free page. InMemoryOrders prices from a catalogue that holds a LAMP at 40.00, and records each cancellation. Outbox keeps each notice instead of sending it:
// Runs each order instruction against a catalogue and a list of cancelled orders
static final class InMemoryOrders extends OrderOpInterpreter<IdKind.Witness> {
final List<UUID> cancelled = new ArrayList<>();
@Override
protected <A> Kind<IdKind.Witness, A> handlePriceOf(OrderOp.PriceOf<A> op) {
return ID.widen(Id.of(op.k().apply(CATALOGUE.get(op.sku()))));
}
@Override
protected <A> Kind<IdKind.Witness, A> handleCancel(OrderOp.Cancel<A> op) {
cancelled.add(op.orderId());
return ID.widen(Id.of(op.k().apply(Unit.INSTANCE)));
}
}
// Keeps each notice in an outbox instead of sending it
static final class Outbox extends NoticeOpInterpreter<IdKind.Witness> {
final List<String> sent = new ArrayList<>();
@Override
protected <A> Kind<IdKind.Witness, A> handleSend(NoticeOp.Send<A> op) {
sent.add(op.text());
return ID.widen(Id.of(op.k().apply(Unit.INSTANCE)));
}
}
Interpreters.combine joins them into one interpreter for the pair, which hands a Left to the first and a Right to the second. LIMIT is 30.00:
InMemoryOrders orders = new InMemoryOrders();
Outbox outbox = new Outbox();
// One interpreter for the pair: each instruction goes to the one for its set
Natural<EitherFKind.Witness<OrderOpKind.Witness, NoticeOpKind.Witness>, IdKind.Witness> both =
Interpreters.combine(orders, outbox);
boolean cancelled =
ID.narrow(
cancelAndTell(ORDER, "LAMP", LIMIT).foldMap(both, Instances.monad(id())).runKind())
.value();
// true
List<String> notices = outbox.sent;
// [Cancelled: LAMP costs 40.00]
Within the limit, as for a BULB, the program cancels nothing and sends nothing.
What the generated code is
An Inject<F, G> puts an instruction from the set F into the larger set G. OrderEffectsSupport's two are the library's injectLeft and injectRight. Written by hand, they draw the HKJ checker's migration-nudge warning, which points you to @ComposeEffects:
// What OrderEffectsSupport's two Injects are: orders go on the left, notices on the right
@SuppressWarnings("migration-nudge") // shows what @ComposeEffects generates
static final Inject<
OrderOpKind.Witness, EitherFKind.Witness<OrderOpKind.Witness, NoticeOpKind.Witness>>
INTO_ORDERS = InjectInstances.injectLeft();
@SuppressWarnings("migration-nudge") // shows what @ComposeEffects generates
static final Inject<
NoticeOpKind.Witness, EitherFKind.Witness<OrderOpKind.Witness, NoticeOpKind.Witness>>
INTO_NOTICES = InjectInstances.injectRight();
An injected instruction is an EitherF, as Working with Kind shows.
Three sets and more
A pair holds two sets. A third nests on the right, and so does a fourth, which is as many as @ComposeEffects and Interpreters.combine take:
Two sets: EitherF<F, G> Three sets: EitherF<F, EitherF<G, H>> Four sets: EitherF<F, EitherF<G, EitherF<H, I>>>
InjectInstances.injectRightThen(inner) reaches into the nesting: injectRightThen(injectLeft()) puts an instruction from G into the three-set nesting, as a Right holding a Left. @ComposeEffects writes each of these for you.
Moving a program into the pair
A program written for OrderOp alone, before notices existed, joins the pair with Free.translate, which passes each instruction through a natural transformation. An Inject's method is one:
// Written for OrderOp alone, before notices existed
FreePath<OrderOpKind.Witness, BigDecimal> lampAndBulb =
Path.free(OrderOpOps.priceOf("LAMP", Function.identity()), OrderOpFunctor.instance())
.zipWith(
Path.free(
OrderOpOps.priceOf("BULB", Function.identity()), OrderOpFunctor.instance()),
BigDecimal::add);
// Each instruction moves to the left of the pair; the program is otherwise unchanged
Free<EitherFKind.Witness<OrderOpKind.Witness, NoticeOpKind.Witness>, BigDecimal> joined =
Free.translate(lampAndBulb.toFree(), INTO_ORDERS::inject, ORDERS_AND_NOTICES);
BigDecimal total =
ID.narrow(
joined.foldMap(
Interpreters.combine(new InMemoryOrders(), new Outbox()),
Instances.monad(id())))
.value();
// 42.50
Each bound constructor works the same way: ORDERS.priceOf builds the OrderOp program and translates it into the pair.
An instruction is never null
EitherF.left(null) and EitherF.right(null) throw at the call, so an instruction in the pair always holds one from a set. Its result follows the rule of the Free program that holds it: a program always gives a value.
Creating instances
@ComposeEffects generates the Injects and the Functor, and each set's generated boundTo gives its constructors in the pair. By hand, InjectInstances.injectLeft(), injectRight() and injectRightThen(inner) give the Injects, EitherFFunctor.of(left, right) the Functor, and EitherF.left(fa) and EitherF.right(ga) an instruction.
Methods
| Method | What it does |
|---|---|
EitherF.left(fa), EitherF.right(ga) | Hold an instruction from the left set, or from the right one |
eitherF.fold(onLeft, onRight) | Act on the instruction from whichever side holds it |
inject.inject(fa) | Put an instruction from one set into a larger one |
Interpreters.combine(f, g), up to four | Join one interpreter per set into one for the nesting |
EitherFFunctor.of(left, right) | The pair's Functor, built from each set's |
Free.translate(program, natural, functor) | Move a program to another instruction set |
XOps.boundTo(inject, functor) | A set's generated constructors, building programs in the larger set |
Working with Kind
An EitherF is already its own Kind, so EITHERF.widen and EITHERF.narrow, from EitherFKindHelper, are casts. An injected instruction narrows to one, and fold says which side holds it:
// An instruction in the pair is an EitherF: Left holds an order instruction, Right a notice
EitherF<OrderOpKind.Witness, NoticeOpKind.Witness, Unit> held =
EITHERF.narrow(
INTO_NOTICES.inject(
NOTICE_OP.widen(new NoticeOp.Send<>(ORDER, "Shipped", Function.identity()))));
// fold acts on whichever side holds the instruction
boolean aNotice = held.fold(_ -> false, _ -> true);
// true
Its only instance is EitherFFunctor, which maps through the instruction on whichever side holds it, using that set's Functor. That is all a Free program needs of its instruction set: EitherF has no Applicative or Monad, because the program is the monad.
When to use EitherF
| You need | Use |
|---|---|
| One program over two or more instruction sets | @ComposeEffects, which generates the EitherF nesting |
| To read a type error in that program, or to join sets by hand | This page's Inject, EitherF and Interpreters.combine |
| One instruction set | Free on its own |
| Two services called directly, run one way | A direct call to each |
Practise joining instruction sets in Tutorial 04: Combining Effects with EitherF (3 exercises), from the Effect Handlers journey.
Benchmarks: FreeEffectBenchmark measures what dispatching through EitherF and Interpreters.combine costs beside a program over one instruction set. Benchmarks & Performance says how to run it.
Previous: Free Applicative Next: Coyoneda