Example Index

Every runnable example in org.higherkindedj.example.basic, with what it shows and the page that explains it.

Each example is a class with a main method in the hkj-examples module. Open the class in your IDE and run it, or run it from the command line:

./gradlew :hkj-examples:run -PmainClass=org.higherkindedj.example.basic.either.EitherExample

A test checks that every runnable class in the package has a row. The build compiles these examples; the code on the book's own pages, in org.higherkindedj.example.book, is tested as well.

Failure

ExampleWhat it showsPage
EitherExampleRight and Left, a chain of flatMaps that stops at the first Left, fold, and recovery with handleErrorWithEither
EitherOrBothExampleA Left, a Right, or Both at once: a result that carries warningsEitherOrBoth
NonEmptyListExampleA list that always holds at least one elementNonEmptyList
TryExampleSuccess and Failure, flatMap, which passes a Failure through, and recovery with recover and recoverWithTry
TryAttemptExampleTry.attempt around Java methods that throw checked exceptionsTry
ValidatedMonadExampleValid and Invalid, flatMap stopping at the first Invalid, and recovery with handleErrorWithValidated
ValidatedAssemblyExampleA record built from fields validated one by one, with every error kept in field orderAccumulating Assembly
GeneratedAssemblyExampleThe companion that @GenerateAssembly generates, with one method per componentAccumulating Assembly

Absence

ExampleWhat it showsPage
MaybeExampleJust and Nothing, map, flatMap, and recovery from Nothing with handleErrorWithMaybe
OptionalExampleJava's Optional through the Kind encoding: map, flatMap, and a default with handleErrorWithOptional

Deferred

ExampleWhat it showsPage
IOExampleConsole effects described with delay, composed with map and flatMap, and run with unsafeRunSyncIO
LazyExampleA computation deferred until force, then kept, so that it runs onceLazy
CompletableFutureExamplemap and flatMap over futures, and a failed future recovered with handleErrorWithCompletableFuture

Virtual threads

ExampleWhat it showsPage
VStreamBasicExampleBuilding a stream, transforming it and running it, its laziness, an effectful unfold, and recoveryVStream
VStreamHKTExampleVStream's instances: code written for any Monad, Foldable's foldMap, and Alternative's orElse and guardHKT and Type Classes
VStreamAdvancedExamplebracket and onFinalize, StreamTraversal, Flow.Publisher, and natural transformations between List and VStreamAdvanced Features

Environment and state

ExampleWhat it showsPage
ReaderExampleValues read from a configuration, chained with flatMap and run with runReaderReader
StateExampleA stack's push and pop as State stepsState
BankAccountWorkflowDeposits and withdrawals threaded through State and composed with ForState
WriterExampleA log kept beside the result with tell, and joined across flatMapWriter

Collections

ExampleWhat it showsPage
ListMonadExamplemap and flatMap on a List, with a step that gives several results or noneList
StreamExampleJava's Stream through the type classes: map, flatMap, taking and dropping, and lazinessStream
PCollectionsExamplePCollections' persistent lists through ListKind, since each is a java.util.ListPCollections Integration

Programs as data

ExampleWhat it showsPage
IdExampleId, which adds nothing: map, flatMap, and StateT over IdIdentity
TrampolineExampleRecursion that does not overflow the stackTrampoline
FreeApplicativeExampleA Free Applicative program built and then interpretedFree Applicative
StaticAnalysisExampleA Free Applicative program read before it runsFree Applicative
PermissionCheckingExampleThe permissions a program of file operations needs, checked before it runsFree Applicative
ParallelDataFetchExampleIndependent fetches held as one program, which an interpreter could run in parallelFree Applicative
CoyonedaExamplemaps held by Coyoneda and applied together by lowerCoyoneda
ConstExampleConst, which holds one value that second leaves alone, and its BifunctorConst

Type classes

ExampleWhat it showsPage
GenericExampleOne function written for any Functor, called on a List and an OptionalWorking with Kind
InstancesFacadeExampleInstances fetched through the Instances facadeObtaining Instances
AlternativeConfigExampleConfiguration read from the first source that has it, with AlternativeAlternative
BifunctorExamplebimap, first and second on two-sided typesBifunctor
ProfunctorExamplelmap, rmap and dimap adapting a function's input and outputProfunctor
FoldableExampleOne structure reduced several ways, with foldMap and different MonoidsFoldable and Traverse
OptionalMonoidExampleData aggregated with firstOptional, maximum and minimumSemigroup and Monoid
UpdateMonoidExampleNamed Updates composed with Monoids.update() and foldedSemigroup and Monoid
NaturalTransformationExampleNatural transformations from one container to anotherNatural Transformation

For comprehensions

ExampleWhat it showsPage
ForComprehensionExampleFor over several monads, among them List, Maybe and StateT: from, when, let and yieldFor Comprehension
ForTraverseComprehensionExampletraverse, sequence and flatTraverse inside For and ForPathFor Comprehension
ForStateExampleForState workflows that update their state through lensesForState Comprehension
MTLCapabilitiesExampleMonadReader, MonadState and MonadWriter, each in a function written against that capability aloneMTL Capabilities
EnhancedOpticsIntegrationExampleForState steps through traversals and Isos, and For's through, on a department's recordsForState Comprehension

Monad transformers

ExampleWhat it showsPage
EitherTExampleValidation with Either over asynchronous CompletableFuture stepsEitherT
MaybeTExampleAsynchronous lookups that may find nothing: a user, then their preferencesMaybeT
OptionalTExampleAsynchronous lookups with Optional: a user, their profile, then their preferences, with a defaultOptionalT
ReaderTExampleThe four ways to build a ReaderT: of, liftF, reader and askReaderT
ReaderTAsyncExampleAn asynchronous workflow that reads its configuration, run against two configurationsReaderT
ReaderTAsyncUnitExampleAn initialisation step that reads its configuration and gives UnitReaderT
StateTExampleStateT over Optional: building one, map and flatMap, and a negative starting state that gives Optional.empty()StateT
StateTStackExampleA stack over Optional, where popping an empty stack gives Optional.empty()StateT
WriterTExampleWriterT over Id: tell, listen and censorWriterT

For Effect Path, optics and whole-application examples, see the Examples Gallery.


Previous: Laws and Where HKJ Bends Them