Identity: The Monad That Adds Nothing
An Id holds a value and adds nothing, so code written for any monad can run with no effect.
| Models | A value and nothing else: no failure, no absence, no delay |
| Replaces | A plain value, where code written for any monad needs one |
| Effect Path | IdPath, a step that cannot fail |
| Instances | Functor, Applicative, Selective, Monad, Foldable, Traverse |
| Choose it when | You run code written for any monad with no effect, in a test or as a transformer's inner monad; otherwise a plain value, or compare every type in Choosing a Type |
- Hold a step that cannot fail on an
IdPath, and join it to a chain that can - Test code written for any monad by running it with
Id - Run a transformer over
Id, and choose between it and the plain type - Predict what
Iddoes withnull, whichIdPathrefuses - Use
Idin generic code through itsMonadandTraverseinstances
The code on this page is IdentityBook.java: the page includes it, so the build compiles and runs it. IdentityBookTest.java holds what the page says each method does.
The monad that adds nothing
Code written for any monad takes a Monad<F> and values of type Kind<F, A>, and never says which monad F is. Something must fill F when you want no effect at all, such as a test that checks only the arithmetic, or a transformer whose inner monad has nothing to do. Id fills it. An Id<A> holds one value, its map and flatMap apply the function to that value, and nothing else happens. On a Path it is an IdPath, a step that cannot fail.
The code on this page uses these imports:
import static org.higherkindedj.hkt.id.IdKindHelper.ID;
import static org.higherkindedj.hkt.instances.Witnesses.id;
import static org.higherkindedj.hkt.instances.Witnesses.io;
import static org.higherkindedj.hkt.io.IOKindHelper.IO_OP;
import java.math.BigDecimal;
import org.higherkindedj.example.book.foundations.Basket;
import org.higherkindedj.example.book.optics.cast.LineItem;
import org.higherkindedj.hkt.Kind;
import org.higherkindedj.hkt.Monad;
import org.higherkindedj.hkt.TypeArity;
import org.higherkindedj.hkt.WitnessArity;
import org.higherkindedj.hkt.effect.EitherPath;
import org.higherkindedj.hkt.effect.IdPath;
import org.higherkindedj.hkt.effect.Path;
import org.higherkindedj.hkt.id.Id;
import org.higherkindedj.hkt.id.IdKind;
import org.higherkindedj.hkt.instances.Instances;
import org.higherkindedj.hkt.io.IO;
import org.higherkindedj.hkt.io.IOKind;
import org.higherkindedj.hkt.state.StateTuple;
import org.higherkindedj.hkt.state_t.StateT;
The basket and its lines are the ones the State page fills: a lamp at 40.00, four bulbs at 2.50, a sofa at 450.00, and a limit of 100.00. The basket's total cannot fail, so it is an IdPath. get() gives the value, and toEitherPath() makes it the first step of a chain that can fail:
// A step that cannot fail, on the Path that adds no effect
IdPath<BigDecimal> subtotal = Path.id(Basket.EMPTY.add(LAMP).add(BULBS)).map(Basket::total);
BigDecimal total = subtotal.get();
// 50.00
// It joins a chain that can fail as the first step of an EitherPath
EitherPath<String, BigDecimal> withinLimit =
subtotal
.<String>toEitherPath()
.via(t -> t.compareTo(LIMIT) <= 0 ? Path.right(t) : Path.left("over the limit"));
toMaybePath() starts a chain that can be empty in the same way.
Testing code written for any monad
This method adds a delivery charge to a total under 50.00. It is written for any monad, so the service can run it in IO and a test in Id. Its bound, F extends WitnessArity<TypeArity.Unary>, says only that F holds one type, as The WitnessArity bound explains:
static final BigDecimal DELIVERY = new BigDecimal("4.99");
static final BigDecimal FREE_FROM = new BigDecimal("50.00");
// Written once for any monad: F might be IO in the service and Id in a test
static <F extends WitnessArity<TypeArity.Unary>> Kind<F, BigDecimal> withDelivery(
Monad<F> monad, Kind<F, BigDecimal> subtotal) {
return monad.map(
total -> total.compareTo(FREE_FROM) >= 0 ? total : total.add(DELIVERY), subtotal);
}
In a test, Id runs it with nothing around the value, so the test reads the total with ID.narrow(...).value():
// In a test, Id runs the arithmetic with no effect around it
Monad<IdKind.Witness> ids = Instances.monad(id());
BigDecimal small = ID.narrow(withDelivery(ids, Id.of(new BigDecimal("12.50")))).value();
// 17.49
BigDecimal large = ID.narrow(withDelivery(ids, Id.of(new BigDecimal("60.00")))).value();
// 60.00
The service passes IO, and the same method adds the charge when the IO runs:
// In the service, the subtotal is read when the IO runs, and so is the charge added
Kind<IOKind.Witness, BigDecimal> subtotalLater =
IO_OP.widen(IO.delay(() -> new BigDecimal("12.50")));
IO<BigDecimal> charged = IO_OP.narrow(withDelivery(Instances.monad(io()), subtotalLater));
BigDecimal served = charged.unsafeRunSync();
// 17.49
A transformer over Id
A transformer takes the monad it wraps as a parameter: StateT<S, F, A> threads a state through steps in F. With Id as F it adds nothing beyond the state, so a StateT<Basket, IdKind.Witness, Boolean> runs as the State page's State<Basket, Boolean> does. Here is that page's basket step, written as a StateT over Id:
// The State page's step, as a StateT over Id: adds the line if the basket stays within the limit
static StateT<Basket, IdKind.Witness, Boolean> add(LineItem line) {
return StateT.create(
basket -> {
Basket bigger = basket.add(line);
return Id.of(
bigger.total().compareTo(LIMIT) <= 0
? new StateTuple<>(true, bigger)
: new StateTuple<>(false, basket));
});
}
// runStateT gives an Id holding the result and the basket the step leaves
StateTuple<Basket, Boolean> after = ID.narrow(add(SOFA).runStateT(Basket.EMPTY)).value();
// The sofa would take the basket past the limit, so the step leaves it out
boolean added = after.value();
// false
The library ships State, Reader and Writer as types of their own, which are shorter to write than a transformer over Id. Reach for the transformer when the code is written for any inner monad, and a test or a caller fixes that monad to Id.
Id holds a null
A traversal's modify runs through Id, so Id holds whatever an element holds. Id.of(null) holds the null, and the monad's map keeps a null that its function returns. IdPath refuses one: Path.id(null) throws NullPointerException, and so does Path.idPath given an Id that holds null. Values, never null sets out the rule for each type.
Creating instances
Id.of(value) wraps a value, and Instances.monad(id()).of(value) does the same through the instance. Path.id(value) starts an IdPath, and Path.idPath(id) turns an Id into one.
Methods
| Method | What it does |
|---|---|
id.value() | Gives the value |
id.map(f), id.flatMap(f) | Apply f to the value; flatMap's function returns an Id |
idPath.map(f), via(f), zipWith(other, f) | The same on the Path; via's function returns an IdPath |
idPath.get(), run() | Give the value, or the Id |
idPath.toEitherPath(), toMaybePath() | Start a chain that can fail, or be empty, with the value |
Working with Kind
Generic code takes Id through its Monad, from Instances.monad(id()), which is IdMonad.instance(). IdTraverse.INSTANCE traverses an Id with any Applicative, and is its Foldable too, and IdSelective.instance() is its Selective. Id implements its own Kind, so Id.of(value) needs no widen, and ID.narrow gives the Id back, as Testing code written for any monad shows.
When to use Id
| You need | Use |
|---|---|
| A test of code written for any monad, with nothing to set up | Id |
| A transformer's inner monad, when the code is written for any | Id, as in StateT<S, IdKind.Witness, A> |
| A state, an environment or a log threaded through steps | State, Reader or Writer |
| A step that cannot fail, in a chain of Paths | IdPath |
| A value in ordinary code | The value itself: Id adds nothing |
Run transformers over Id in Tutorial 04: Polymorphic Capabilities (14 exercises).
Previous: Stream Next: Trampoline