liveBook · Manning

Read-only environment

As explained in Learn Haskell by Example

A read-only environment is shared contextual data that computations can inspect or access without modifying.

A read-only environment is shared contextual data that computations can inspect without modifying. In a file-synchronization application, configuration such as source and destination paths, file-type filters, recursion limits, and transfer limits belongs in this environment. section 15.1.1 section 15.1

Use the Reader abstraction to avoid threading configuration through every action:

  • Reader r a reads an environment of type r and produces a result of type a. section 15.1.1
  • ask retrieves the current environment inside a Reader computation, while runReader supplies the environment from outside. section 15.1.1
  • ReaderT adds the same read-only capability to another monad, such as IO, allowing configuration access alongside effectful operations. section 15.1.1

Reading synchronization paths

Define type App a = ReaderT Config IO a. An action can use ask to obtain Config, select configFromPath and configToPath, and use liftIO to print or otherwise perform IO. Running runReaderT example cfg supplies the shared configuration once instead of passing cfg through every action.

How Learn Haskell by Example covers it

How deep it goes
Explains Reader, ask, runReader, ReaderT, and lifting into IO, but does not descend into transformer implementation internals.
Examples
Uses synchronization configuration, integer environments, conditional environment reading, and a ReaderT action that prints source and destination paths.
What you can do after
Apply it via ReaderT to share configuration across IO actions without repeatedly passing the environment as an argument.
How it connects
Connects read-only environments with Reader, ReaderT, IO, monad transformers, StateT, WriterT, and RWST.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.