ForState: Named State Comprehensions
Keep a chain's values in a record's named fields, and change them through lenses.
"The limits of my language mean the limits of my world."
— Ludwig Wittgenstein, Tractatus Logico-Philosophicus (5.6, trans. C. K. Ogden)
A tuple gives a chain a language of _1 to _12, and what you can say about each value shrinks to match. ForState gives each value a name.
- Start a
ForStatefrom a value you have withwithState, or from aForchain withtoState - Change a record's fields through lenses with
update,modifyandmodifyVia - Guard the chain with
when, given aMonadZero - Edit a collection field with
traverse, a field in another form withmodifyVia, and part of the record withzoom - Say when each step runs, and how
ForStatediffers from the State monad
The code on this page is ForStateBook.java, with Checkout.java: the page includes both, so the build compiles and runs them. ForStateBookTest.java holds what the page says each step does.
When tuple positions stop reading well
In plain Java, each step's result goes in a local variable with a name. A For chain keeps its values in a tuple instead, and by the fourth or fifth value t._4() says nothing about what it holds. Insert a step, and every later position moves. ForState keeps the values in a record you declare, and each step reads and writes them by name, through lenses. A For chain stops at twelve values, and a record has as many fields as you give it.
An Effect Path has no ForState. On a Path, map with a lens changes a record, as in path.map(order -> OrderLenses.status().set(OrderStatus.PAID, order)), and via runs a step with an effect. This page is for a chain over Kind, written once for any container with a Monad.
The code on this page uses these imports, with Order, Customer and EmailAddress from the order records the Optics chapter introduces, and their generated lenses:
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.maybe.MaybeKindHelper.MAYBE;
import java.math.BigDecimal;
import java.util.function.Function;
import org.higherkindedj.example.book.foundations.foroptics.ForOpticsBook;
import org.higherkindedj.example.book.optics.cast.Customer;
import org.higherkindedj.example.book.optics.cast.CustomerLenses;
import org.higherkindedj.example.book.optics.cast.EmailAddress;
import org.higherkindedj.example.book.optics.cast.Order;
import org.higherkindedj.example.book.optics.cast.OrderLenses;
import org.higherkindedj.example.book.optics.cast.OrderStatus;
import org.higherkindedj.hkt.Kind;
import org.higherkindedj.hkt.Monad;
import org.higherkindedj.hkt.MonadZero;
import org.higherkindedj.hkt.TypeArity;
import org.higherkindedj.hkt.WitnessArity;
import org.higherkindedj.hkt.either.Either;
import org.higherkindedj.hkt.either.EitherKind;
import org.higherkindedj.hkt.expression.For;
import org.higherkindedj.hkt.expression.ForState;
import org.higherkindedj.hkt.instances.Instances;
import org.higherkindedj.hkt.maybe.Maybe;
import org.higherkindedj.hkt.maybe.MaybeKind;
import org.higherkindedj.optics.util.Traversals;
Two ways in
ForState starts from a whole value, so every field of the record has a value before the first step runs. There are two ways in:
ForState.withState(monad, value)starts from a value you already have, such as an order to update.toState(build), as a step of aForchain, builds the record from the values the chain has bound, taking one parameter per value, or the tuple. It is there at every arity, from one value to twelve.
Never fill a field with null for a later step to set. Gather the values with For first, and build the record with toState once you have them all, so that every field holds a value from the start, as Values, never null asks.
Given a MonadZero, withState and toState give a chain with when and matchThen, as For.from gives one with when.
Updating an order
inStock checks a line against what the warehouse holds:
// What the warehouse holds of each SKU; it holds no chairs
static final Map<String, Integer> STOCK = Map.of("LAMP", 3, "BULB", 20, "DESK", 1);
static Kind<MaybeKind.Witness, LineItem> inStock(LineItem line) {
return STOCK.getOrDefault(line.sku(), 0) >= line.quantity()
? MAYBE.just(line)
: MAYBE.nothing();
}
pay starts from the order, with MAYBE_MONAD as Instances.monadZero(maybe()), and its steps run in order:
whenlets only a new order through.traversechecks every line withinStock, and oneNothingends the chain.modifyVialower-cases the customer's email as text.andThenjoins two lenses, from the order to its customer and on to the email.updatemarks the order paid.
// Pay for a new order: every line must be in stock, and the email is kept in lower case
public static Maybe<Order> pay(Order order) {
return MAYBE.narrow(
ForState.withState(MAYBE_MONAD, MAYBE.just(order))
.when(current -> current.status() == OrderStatus.NEW)
.traverse(OrderLenses.lines(), Traversals.forList(), ForStateBook::inStock)
.modifyVia(
OrderLenses.customer().andThen(CustomerLenses.email()),
ForOpticsBook.EMAIL_TEXT,
String::toLowerCase)
.update(OrderLenses.status(), OrderStatus.PAID)
.yield());
}
EMAIL_TEXT is the Iso from For with Optics:
// An EmailAddress holds one String, so the two convert both ways without loss
public static final Iso<EmailAddress, String> EMAIL_TEXT =
Iso.of(EmailAddress::value, EmailAddress::new);
ORDER is a new order of a lamp and four bulbs, its email typed with capitals. SHIPPED has shipped, and BACKORDERED asks for a chair:
Maybe<String> paid =
pay(ORDER).map(order -> order.status() + " " + order.customer().email().value());
// Just(PAID ada@example.com)
Maybe<Order> alreadyShipped = pay(SHIPPED);
// Nothing
Maybe<Order> backordered = pay(BACKORDERED);
// Nothing
Gathering, then naming
A receipt needs an order, a verified email and a total, and the first two come from steps with an effect. For gathers them, and toState names them in a Checkout, with total summing each line's price times its quantity. @GenerateLenses generates the checkout's lenses as CheckoutLenses:
/** A checkout in progress: the order, the address its receipt goes to, and what it costs. */
@GenerateLenses
public record Checkout(Order order, EmailAddress sendTo, BigDecimal total) {
public Checkout {
Objects.requireNonNull(order, "order");
Objects.requireNonNull(sendTo, "sendTo");
Objects.requireNonNull(total, "total");
}
}
// For gathers the order and a verified email; toState names them, with the total, in a Checkout
public static <F extends WitnessArity<TypeArity.Unary>> Kind<F, String> receipt(
Monad<F> monad,
Kind<F, Order> found,
Function<Customer, Kind<F, EmailAddress>> verify,
BigDecimal discount) {
return For.from(monad, found)
.from(order -> verify.apply(order.customer()))
.toState((order, email) -> new Checkout(order, email, total(order)))
.modify(CheckoutLenses.total(), total -> total.subtract(discount))
.zoom(CheckoutLenses.order())
.update(OrderLenses.status(), OrderStatus.PAID)
.endZoom()
.yield(
checkout ->
checkout.order().status()
+ ": "
+ checkout.total()
+ " to "
+ checkout.sendTo().value());
}
zoom narrows the chain to the order inside the checkout, so the update after it takes a lens on Order, and endZoom widens it back to the whole Checkout. With Either's instance, a Left from verify stops the chain before toState builds anything:
Monad<EitherKind.Witness<String>> eitherMonad = Instances.monad(either());
BigDecimal discount = new BigDecimal("5.00");
Either<String, String> sent =
EITHER.narrow(
receipt(
eitherMonad,
EITHER.widen(Either.right(ORDER)),
customer -> EITHER.widen(Either.right(new EmailAddress("ada@example.com"))),
discount));
// Right(PAID: 45.00 to ada@example.com)
Either<String, String> unverified =
EITHER.narrow(
receipt(
eitherMonad,
EITHER.widen(Either.right(ORDER)),
customer -> EITHER.widen(Either.left("email not verified")),
discount));
// Left(email not verified)
Every step
| Step | What it does | Built on |
|---|---|---|
update(lens, value) | Sets a field | map |
modify(lens, f) | Runs f on a field | map |
from(f) | Runs an effect, and keeps the record as it was | flatMap |
fromThen(f, lens) | Runs an effect, and stores its value through the lens | flatMap |
when(test) | Gives the instance's empty value when test fails | MonadZero's filter |
matchThen(source, prism, target) | Reads the source field, matches it with the prism, and stores the case through target; gives the empty value on a miss | flatMap |
matchThen(extract, target) | The same, with a function that gives an Optional | flatMap |
traverse(lens, traversal, f) | Runs f, which has an effect, on every element of a collection field, and stores the results | the traversal's modifyF, which runs f on each element inside the instance |
traverseOver(traversal, f) | The same, where the record is itself the collection | the traversal's modifyF |
modifyThrough(traversal, f) | Runs a plain f on every element the traversal reaches; a second form takes a lens into each element | map |
modifyVia(lens, iso, f) | Runs f on the field in the Iso's other form, as modify(lens.andThen(iso), f) would | map |
updateVia(lens, iso, value) | Sets the field to the Iso's reverseGet of value | map |
zoom(optic) … endZoom() | Between the two, update, modify and fromThen take lenses on the part the optic reaches | the optic's get and set |
yield() or yield(f) | Ends the chain with the record, or with f of it | Nothing, or map |
when and both matchThen steps are there only on a chain that started from a MonadZero. zoom takes a Lens, a FocusPath (the lens path @GenerateFocus writes) or an Iso. On a chain started from a MonadZero it also takes an AffinePath, a path to a part that may be absent, and gives the empty value when it is.
For has a traverse step too, which takes a Traverse instance and binds the collected results as a new value, as Traversing inside a chain shows. ForState's takes a lens and a traversal optic, and writes the results back into the record.
Things people get wrong
- "
ForStateis the State monad." It carries a record through anyMonad'smapandflatMap,Either's included. For the State effect, seeMonadStatein For with MTL Capabilities. - "The steps run at
yield." Each step calls the instance'smaporflatMapas you add it. OverMaybeorEither, a step's function runs then. OverIO, nothing runs until you run the result. - "
ForStateis better thanForpast three steps." It needs a record and a lens for each field. For a short chain,For's tuple is less to write, and Which comprehension should you use? helps you choose.
- For Comprehensions: the chain
toStatestarts from - For with Optics:
focus,throughandmatchin aForchain, andForTraversal - Lenses and Isomorphisms: the optics the steps take
Practise ForState in the ForState journey (13 exercises), and its traversal and Iso steps, with For's through, in Tutorial 04: Enhanced Optics Integration (10 exercises).
Previous: For with MTL Capabilities Next: Core Types