Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

This manual describes exchangealgebra-0.6.1.1. With ExchangeAlgebra, you record transactions in Haskell as sums of exchange algebra terms, keep journals, carry out bookkeeping procedures, and prepare financial statements. It covers four layers of the library: Algebra, Journal, Accounting, and IO. Start with From journal entries to exchange algebra to see how a journal table corresponds to the algebraic notation. For module documentation and the full API, see the Haddock reference on Hackage.

How this manual is organized

The running example starts with a bank withdrawal on January 10 and follows the shop’s January transactions through closing and financial statements. On February 1, the shop forms a subsidiary and prepares an opening consolidated balance sheet.

Mathematical foundations

Getting started

Customizing the components

  • In Elements, add a bank element and query bases by bank.
  • In Bases, build a three-element base and update account access.
  • In Redundant and exchange algebras, choose an amount type, work with the month’s terms, and read debit and credit differences.

Transfers and journals

  • In Transfers, move part of the rent payment to prepaid expenses and check the resulting balances.
  • In Journals, attach dates and descriptions to transactions and select terms for January.
  • In Multiple accounting entities, record the withdrawal for both the shop and the bank and check each entity’s terms.

Account titles

Bookkeeping procedures

  • In Checking a journal, express dollar cash in yen and validate the January records for bookkeeping.
  • In Trial balance and checks, compute debit and credit totals and balances by account and diagnose a missing opening balance.
  • In Adjusting entries, defer the rent for the next period and record the inventory count.
  • In Closing entries, close the revenue and expense accounts and inspect the post-closing trial balance.
  • In Financial statements, prepare January’s income statement and balance sheet.
  • In Consolidation, eliminate the shop’s investment against the subsidiary’s capital to prepare the February 1 consolidated balance sheet.

Input and output

From journal entries to exchange algebra

This page maps a journal written as a debit and credit table onto exchange algebra notation, using four transactions of a small shop. It assumes familiarity with double-entry bookkeeping and no knowledge of the algebra. Definitions and axioms gives the formal definitions.

A journal as a table

Table 1 records the four transactions in a conventional journal. Each row has one debit account and one credit account with the same amount.

No.TransactionDebitAmountCreditAmount
1The owner invests cash.Cash1,000Capital stock1,000
2The shop buys goods for cash.Purchases600Cash600
3The shop sells goods on credit.Accounts receivable900Sales900
4The shop collects part of the receivable.Cash500Accounts receivable500

Table 1. Four journal entries of a small shop. The debit total and the credit total are both 3,000.

The same journal in exchange algebra

Exchange algebra writes an entry as a sum of terms $a : e$, where $a$ is a nonnegative amount and $e$ is a base. Here a base is an account title in angle brackets. A base with Not, such as $\langle \text{Cash} \rangle$, records an increase. A base with Hat, such as $\widehat{\langle \text{Cash} \rangle}$, records a decrease. The four rows of Table 1 become:

$$ \begin{aligned} x_1 &= 1000 : \langle \text{Cash} \rangle + 1000 : \langle \text{Capital stock} \rangle \\ x_2 &= 600 : \langle \text{Purchases} \rangle + 600 : \widehat{\langle \text{Cash} \rangle} \\ x_3 &= 900 : \langle \text{Accounts receivable} \rangle + 900 : \langle \text{Sales} \rangle \\ x_4 &= 500 : \langle \text{Cash} \rangle + 500 : \widehat{\langle \text{Accounts receivable} \rangle} \end{aligned} $$

The terms carry neither debit and credit labels nor minus signs. Each term states which account changed and in which direction. The journal side follows from the account’s division: an increase in an asset or expense is a debit, and an increase in a liability, equity, or revenue account is a credit. A decrease takes the opposite side. For example, the increase in capital stock in $x_1$ is a credit, and the decrease in cash in $x_2$ is also a credit. Account classes and sides gives the full rule, including contra accounts.

The combined record is the sum $x = x_1 + x_2 + x_3 + x_4$ of eight terms. The sum keeps every term: cash has $1000$ and $500$ on the base with Not and $600$ on the base with Hat. Bar, written $\bar{x}$, totals the two directions at each base and keeps the excess. For cash it leaves $900 : \langle \text{Cash} \rangle$, the cash balance.

Recover the debit and credit columns

The projection decL selects the debit terms of $x$ and decR selects the credit terms. decL returns cash 1,000, purchases 600, accounts receivable 900, and cash 500, which is the debit column of Table 1. decR returns the credit column. Both totals are 3,000, so balance returns True.

A program that builds the journal of Table 1 and checks these results needs only the ExchangeAlgebra module:

import ExchangeAlgebra

journal :: Alg MoneyDecimal (HatBase AccountTitles)
journal = 1000 .@ Not :< Cash               .+ 1000 .@ Not :< CapitalStock
       .+  600 .@ Not :< Purchases          .+  600 .@ Hat :< Cash
       .+  900 .@ Not :< AccountsReceivable .+  900 .@ Not :< Sales
       .+  500 .@ Not :< Cash               .+  500 .@ Hat :< AccountsReceivable

main :: IO ()
main = do
    print (norm (decL journal), norm (decR journal))
    print (balance journal)
    print (bar (projByAccountTitle Cash journal))

It prints:

(3000,3000)
True
900:@Not:<Cash

.@ attaches an amount to a hat base. .+ keeps the terms of both operands, including terms on the same base. norm totals the amounts. bar offsets the increases and decreases of the cash terms selected by projByAccountTitle and leaves the net increase of 900.

Definitions and axioms

Note: The mathematical definitions are optional background for using the library. If you prefer to skip the mathematics, go to Installation and modules.

Element structure

Definition 1 (Element structure). Each element set $E$ has a distinguished wildcard element $\# \in E$ and a total order $\leq$. For a query element $p$ and a stored element $e$ in $E$, one-way matching is defined by

$$ p \trianglerighteq e \quad\Longleftrightarrow\quad (p=\#)\lor(p=e). $$

A stored $\#$ indicates that the corresponding element set does not apply. A query for a specific firm therefore skips a term whose firm element is $\#$. The wildcard is an ordinary member of the total order; matching does not define that order.

Definition 1 of the preprint gives a symmetric comparison. The query relation used here treats only a query-side $\#$ as a pattern.

Usage: Elements.

Bases

Definition 2. A base is a tuple of elements, one from each element set. For element sets $E_1,\ldots,E_n$, the base space is $E_1\times\cdots\times E_n$. An account and a firm, for example, form a base with two elements. A query tuple matches a stored base exactly when each query element matches the corresponding stored element.

Here, “element” refers to a member of an element set that supplies a component of a base, while a “member of the redundant algebra” is a sum of terms.

Usage: Bases.

Hat bases and terms

Definition 3. A hat base pairs a base with one of two directions: Not (increase) or Hat (decrease). A query can select both directions with HatNot. Each term has a direction of Not or Hat.

A term pairs a hat base with a nonnegative real amount from the value domain $V\subseteq\mathbb{R}_{\geq 0}$. We write $a:e$ for an increase and $a:\widehat{e}$ for a decrease at the base $e$. The redundant algebra is generated by its terms. In Haskell, Posting is the type that represents a term.

Usage: Bases and Amount types.

Redundant algebra and linear combinations

Definition 4. A redundant algebra consists of finite collections of terms, with addition, scalar multiplication by nonnegative values, hat, bar, and a norm into the value domain.

Usage: Operations and Amount types.

Definition 5. At each underlying base $e_i$, a member of the redundant algebra records two finite sequences of amounts. Write $f_i(e_i)=\langle A_i,B_i\rangle$, with $A_i$ the increase sequence and $B_i$ the decrease sequence. Two increases of 3 and 2 at the same base remain separate terms until an operation explicitly combines them. A member of the redundant algebra $x=\langle f_1,\ldots,f_n\rangle$ has finite support over the bases. An empty sequence pair contributes zero.

Usage: Add the month’s transactions.

Operations

Definition 6. The operations on the paired sequences are as follows.

OperationEffect
HatSwap the two sequences at each base, preserving every amount.
BarTotal each sequence at each base and cancel the two totals. Keep the excess on the larger side and drop a zero remainder.
SumConcatenate the corresponding sequences.
Scalar multiplicationMultiply every amount by the same nonnegative scalar.
NormSum all amounts on both sides over all bases.

The library adds compress, which sums amounts separately for each base and each direction (Hat or Not).

For bar, write $[z]_+=\max(0,z)$. If $A_i=(a_{i1},\ldots,a_{ip_i})$ and $B_i=(b_{i1},\ldots,b_{iq_i})$, the remaining increase and decrease are

$$ D_i=\left[\sum_j a_{ij}-\sum_k b_{ik}\right]_+, \qquad R_i=\left[\sum_k b_{ik}-\sum_j a_{ij}\right]_+. $$

For example, two increases of 3 and 2 and a decrease of 4 on the same base have norm 9. Applying compress gives an increase of 5 and a decrease of 4. Bar leaves an increase of 1. In general, the contribution to the norm is

$$ \operatorname{norm}(f_i(e_i)) = \sum_{j=1}^{p_i} a_{ij} + \sum_{k=1}^{q_i} b_{ik}. $$

Usage: Select an operation.

Five axioms

Let $x=\langle f_1,\ldots,f_n\rangle$ and let $a$ be a nonnegative scalar.

  1. Hat is an involution. Applying hat twice restores the original terms.

    $$ \widehat{\widehat{f_i}}(e_i) = f_i(e_i). $$

  2. Scaling at one base. The scalar acts on each amount in each sequence.

    $$ a \ast f_i(e_i) = \langle a \ast A_i, a \ast B_i\rangle. $$

  3. Scaling across bases. The scalar acts on every component.

    $$ a \ast \langle f_1,\ldots,f_n\rangle = \langle a \ast f_1,\ldots,a \ast f_n\rangle. $$

  4. Norm homogeneity. Scaling the terms scales their total.

    $$ \operatorname{norm}(a \ast x) = a \cdot \operatorname{norm}(x), \qquad a \ge 0. $$

  5. Norm additivity. Adding terms adds their totals.

    $$ \operatorname{norm}(f_i(e_i)+g_i(e_i)) = \operatorname{norm}(f_i(e_i)) + \operatorname{norm}(g_i(e_i)). $$

The preprint lists the defining sum of the norm under the name “norm homogeneity.” The homogeneity law above follows from that sum and the scalar multiplication.

Axioms 4 and 5 hold exactly with exact decimal arithmetic when the amounts, intermediate sums, and products are representable. With binary floating-point arithmetic, summing stored amounts exactly and rounding once still permits the two sides to differ in the last digit: scaling can round individual products, and adding two norms can use two already rounded totals.

Usage: Choose an amount type.

Account classes and sides

Definition 7. An exchange base carries an account title with an account division and a home side. Its debit or credit side combines that home side with the direction. In the library, whatPIMO classifies the account as plus stock, input, minus stock, or output, and fixedCurrent classifies it as current, fixed, or other. Table 1 shows how the directions map to sides for ordinary accounts.

DivisionNotHat
AssetsIncrease (debit)Decrease (credit)
Liabilities, equityIncrease (credit)Decrease (debit)
RevenueRecognition (credit)Reversal (debit)
ExpensesRecognition (debit)Reversal (credit)

Table 1. The meaning of Not and Hat and the resulting side, by account division.

This table also appears as Table 2 in Record a withdrawal.

A contra account reverses the home side of its division before the direction is applied.

Usage: Base and hat base and Classify an account and check its side.

Debit and credit decomposition

Definition 8. An exchange algebra extends the redundant algebra with four decompositions. decL selects debit terms (left), and decR selects credit terms (right). The other two decompositions select by direction. decP selects terms with Hat, and decM selects terms with Not. For example, a decrease in cash is a credit, and an increase in an ordinary expense is a debit. A sum of terms is balanced when its exact debit and credit totals agree.

Usage: Split an entry into debits and credits and Read the debit and credit difference.

Transfers

Definition 9. A transfer table is an ordered collection of triples $(b_i,a_i,f_i)$, where $b_i$ is a source base, $a_i$ is a destination base, and $f_i:V\to V$ transforms a nonnegative amount. Applying the table moves the selected amounts from their source bases to their destination bases according to those transformations. The source base, destination base, and value transformation are separate parts of each rule.

A source wildcard matches any stored element. A destination wildcard retains the corresponding source element. For an accounting reclassification, the amount removed from the source equals the amount added at the destination.

The rules of the algebra layer are sorted by source pattern, as in the preprint. The accounting transfer table preserves written row order and permits a destination to match a later source, but rejects a match with the source of the same or an earlier row; see Transfers.

Usage: Transfers.

Notes

Definition 10. A note set $N$ is a totally ordered set with equality and a distinguished empty element $\mathrm{plank}\in N$. A note can contain a date, a description, or a transaction identifier.

Usage: Declare a note type.

Finite journals

Definition 11. A journal is a finite-support function $J:N\to E$, where $E$ is the exchange algebra. A note outside the support has value zero. Equivalently, the journal is the finite collection of its nonzero note-algebra pairs $(n,J(n))$. Equal notes identify the same algebra component.

Usage: Attach notes to the month.

Journal operations

Definition 12. Hat and scalar multiplication act separately on each note’s algebra, preserving its note. Addition combines the algebras at each equal note by redundant addition:

$$ (J_1+J_2)(n)=J_1(n)+J_2(n). $$

Aggregation combines the note components under the empty note. Its algebra is $\sum_{n\in N}J(n)$; applying bar to that combined algebra gives the journal bar. The norm counts all amounts across notes:

$$ \operatorname{norm}(J)=\operatorname{norm}\left(\sum_{n\in N}J(n)\right). $$

A note projection selects note keys; a base projection selects terms within the selected notes. A joint projection restricts both. Neither projection requires aggregation or cancellation.

Usage: Select by note, base, and date and Total amounts and combine notes.

Definitions 1–12 follow Appendix A of Accounting State Space as a Foundation for Economic Agent-Based Modeling: An Input–Output Benchmark and Inventory Extension, with the query matching and norm clarification stated in Definitions 1 and 6.

Installation and modules

This manual uses exchangealgebra-0.6.1.1 from Hackage. The examples assume that you can write Haskell programs and have Stack installed. They use GHC 9.10.3 with the Stackage snapshot lts-24.65.

The Algebra layer provides types for elements, bases, amounts, and finite sequences of terms. Its operations implement the redundant algebra. Accounting adds the interpretation of account titles and the debit and credit sides.

Add the package to a Stack project

In your project’s stack.yaml, select the snapshot and add the Hackage release as an extra dependency:

resolver: lts-24.65
packages:
- .
extra-deps:
- exchangealgebra-0.6.1.1

Add the library to your package.yaml dependencies. Preserve any other dependencies your program needs:

dependencies:
- base
- exchangealgebra == 0.6.1.1

extra-deps selects the package source for Stack; the dependency in package.yaml makes the library available to your program. Run stack build in the project directory to build the project and its dependencies. For a Cabal project, put exchangealgebra == 0.6.1.1 in the component’s build-depends instead.

Choose imports by layer

ExchangeAlgebra is a convenience module. It re-exports named selections of the Algebra API, account titles and classifications, accounting exchange operations, transfers and closing, trial-balance readouts, statement presentation, CSV and bookkeeping output, and money types. It does not re-export every public module. Import journal functions with import qualified ExchangeAlgebra.Journal as Journal and the operator with import ExchangeAlgebra.Journal ((.|)). Import matchesQuery directly from ExchangeAlgebra.Algebra.Element.

The module table lists public entry points in 0.6.1.1. Import a specific module to restrict the imported names to that part of the library.

LayerModules to importPurpose
AlgebraExchangeAlgebra.AlgebraElements, bases, the Alg type, and redundant-algebra operations.
AlgebraExchangeAlgebra.Algebra.Element, .Base, .Core, .ValueIndividual parts of the algebra; these abbreviated names share the prefix ExchangeAlgebra.Algebra.
AlgebraExchangeAlgebra.Algebra.Posting, ExchangeAlgebra.Algebra.TransferChecked term construction and generic transformations of bases.
JournalExchangeAlgebra.Journal, ExchangeAlgebra.Journal.TransferTerms indexed by notes, and transformations of those journals. Qualify function names shared with Algebra and import the operator .| unqualified.
AccountingExchangeAlgebra.Accounting, ExchangeAlgebra.Accounting.Account, ExchangeAlgebra.Accounting.ExchangeAccount titles, account classification, and debit and credit operations.
AccountingExchangeAlgebra.Accounting.TrialBalance, .Entries, .Closing, .Statements, .ConsolidationBookkeeping procedures; these abbreviated names share the prefix ExchangeAlgebra.Accounting.
IOExchangeAlgebra.IO.Input, ExchangeAlgebra.IO.Input.Admission, ExchangeAlgebra.IO.OutputExternal input, journal checks, and output.

The Simulation layer is outside the scope of this manual.

For the account divisions and side decompositions, ExchangeAlgebra.Accounting.Exchange provides ExBaseClass with whatDiv and whichSide, and Exchange with decL, decR, and balance. decL selects debit terms and decR selects credit terms. balance compares their exact totals before rounding. The journal example uses these functions through ExchangeAlgebra.

When the project builds, continue with Record a withdrawal.

Record a withdrawal

You need knowledge of double-entry bookkeeping and a Stack project prepared as described in Installation and modules. The program on this page records one journal entry in exchange algebra, separates its debits and credits, and checks that their totals agree. You can adapt it to your own entries without reading the chapters on customization.

Transaction and journal entry

On January 10, a business withdraws 3,000 yen from its savings account at Bank A and keeps it as cash. Table 1 shows the journal entry.

DateDescriptionDebitAmountCreditAmount
January 10Savings account at Bank ACash3,000Deposits3,000

Table 1. The journal entry for the withdrawal, in yen.

Run the program

Save the following program as Main.hs in your project directory:

{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}

module Main where

import ExchangeAlgebra hiding (Yen, Dollar)

-- | The unit of an amount.
data Unit = Yen | Dollar | Unit
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Element Unit where
    wildcard = Unit

-- | Read and replace the account title in a base.
instance ExBaseClass (HatBase (AccountTitles, Unit)) where
    getAccountTitle (_ :< (account, _)) = account
    setAccountTitle (direction :< (_, unit)) account = direction :< (account, unit)

-- | January 10: withdraw 3,000 yen from a savings account at Bank A.
withdrawal :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
withdrawal = 3000 .@ Not :< (Cash, Yen)
          .+ 3000 .@ Hat :< (Deposits, Yen)

-- | Print the entry, its debit terms, its credit terms, and the balance check.
main :: IO ()
main = do
    print withdrawal
    print (decL withdrawal)
    print (decR withdrawal)
    print (balance withdrawal)

Run these commands from the project directory:

stack exec -- ghc -Wall -Werror Main.hs -o withdrawal
./withdrawal

The program prints:

3000:@Not:<(Cash,Yen) .+ 3000:@Hat:<(Deposits,Yen)
3000:@Not:<(Cash,Yen)
3000:@Hat:<(Deposits,Yen)
True

The following sections explain the program in the order in which its type is built: elements, a base and hat base, a redundant algebra, and an exchange algebra. Each section shows again the part of the program that it explains.

Elements: AccountTitles and Unit

An element is one piece of the information that identifies what changes. This entry uses two kinds of elements:

  • AccountTitles is the built-in type of account titles. Cash and Deposits are two of its values, and Deposits denotes savings deposits.
  • Unit is the type that the program declares for units. Yen and Dollar are units. The value Unit is the wildcard: it means “any unit” in a query and “no applicable unit” in a recorded term.

The program imports the library and declares Unit:

import ExchangeAlgebra hiding (Yen, Dollar)

-- | The unit of an amount.
data Unit = Yen | Dollar | Unit
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Element Unit where
    wildcard = Unit

The deriving clause and the instance Element Unit make the new type usable as an element type. The import hides the library’s Yen and Dollar because their names collide with the new values.

The program does not use the date or the bank as an element, so its balances do not distinguish dates or banks.

Base and hat base: HatBase (AccountTitles, Unit)

A base is a tuple of elements. (Cash, Yen) is the base for cash in yen, and (Deposits, Yen) is the base for savings deposits in yen. A hat base pairs a base with a direction through :<. The definition of withdrawal contains two hat bases, Not :< (Cash, Yen) and Hat :< (Deposits, Yen):

-- | January 10: withdraw 3,000 yen from a savings account at Bank A.
withdrawal :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
withdrawal = 3000 .@ Not :< (Cash, Yen)
          .+ 3000 .@ Hat :< (Deposits, Yen)

The direction Not represents an increase, and Hat represents a decrease. For revenue and expenses, they represent recognition and reversal, respectively. The amount is nonnegative in both directions. The direction and the account’s division together determine the debit or credit side, as Table 2 shows.

DivisionNotHat
AssetsIncrease (debit)Decrease (credit)
Liabilities, equityIncrease (credit)Decrease (debit)
RevenueRecognition (credit)Reversal (debit)
ExpensesRecognition (debit)Reversal (credit)

Table 2. The meaning of Not and Hat and the resulting side, by account division.

Cash and deposits are assets. Thus Not :< (Cash, Yen) is an increase in cash on the debit side, and Hat :< (Deposits, Yen) is a decrease in deposits on the credit side.

For a contra account, read the direction as a change in that account itself. Not on AccumulatedDepreciation is an increase in accumulated depreciation and falls on the credit side.

Note: The side that increases CashOverShort, IncomeSummary, or SuspenseAccount depends on the context. The library gives them the same sides as assets: Not is a debit and Hat is a credit.

Redundant algebra: Alg

Alg MoneyDecimal (HatBase (AccountTitles, Unit)) is the type of a redundant algebra. Its first argument is the amount type, and its second is the hat base type. MoneyDecimal stores decimal amounts without binary rounding.

In the definition of withdrawal, .@ attaches an amount to a hat base to make a term, and .+ adds the two terms:

-- | January 10: withdraw 3,000 yen from a savings account at Bank A.
withdrawal :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
withdrawal = 3000 .@ Not :< (Cash, Yen)
          .+ 3000 .@ Hat :< (Deposits, Yen)

The first line of the output is this sum. Addition keeps every term, even on the same base. To net the terms on each base, apply bar explicitly.

Exchange algebra: ExBaseClass

The instance of ExBaseClass defines where the account title is in the base. getAccountTitle reads the title, and setAccountTitle replaces it while keeping the direction and the unit. FlexibleInstances permits this instance declaration.

-- | Read and replace the account title in a base.
instance ExBaseClass (HatBase (AccountTitles, Unit)) where
    getAccountTitle (_ :< (account, _)) = account
    setAccountTitle (direction :< (_, unit)) account = direction :< (account, unit)

With this instance, the redundant algebra is an exchange algebra, and three more functions are available. main prints their results after the sum:

-- | Print the entry, its debit terms, its credit terms, and the balance check.
main :: IO ()
main = do
    print withdrawal
    print (decL withdrawal)
    print (decR withdrawal)
    print (balance withdrawal)
  • decL selects the debit (left) terms, which form the second line of the output.
  • decR selects the credit (right) terms, which form the third line.
  • balance compares the debit and credit totals. The last line, True, means that they agree.

balance compares amounts only. It does not detect a wrong account title or convert between units, so apply it to terms in a single unit.

Use the program for your entry

To record another entry in yen, change three parts of each term in withdrawal:

  1. Replace the account title with one from Built-in account titles.
  2. Select Not or Hat from Table 2.
  3. Replace 3000 with a nonnegative amount. .@ stops with an error for a negative amount.

If the entry has more than two terms, join the additional terms with .+. Run the program again, and check that the last line is True.

If this form is sufficient, continue with Transfers. To customize it, read the chapter for the component that you want to change:

Tested with exchangealgebra-0.6.1.1 on 2026-11-22.

Elements

Add or change the element types in the program from Record a withdrawal. This chapter adds a bank element and shows how to query it.

Add a bank element

Add a Bank type to distinguish deposits held at different banks. Its wildcard follows the Element structure of Definition 1.

-- | The bank where a deposit is held.
data Bank = BankA | BankB | Bank
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Element Bank where
    wildcard = Bank

BankA and BankB identify banks. The Bank constructor is the wildcard. The derived instances supply equality, ordering, display, and hashing. GHC supplies Typeable. For this new element type, implement wildcard.

Add Bank as the third type in (AccountTitles, Unit, Bank). Tuples of two through seven element types have Element instances. The cash term has no applicable bank, so its base stores Bank. The deposit term stores BankA.

-- | Cash has no applicable bank.
cashBase :: (AccountTitles, Unit, Bank)
cashBase = (Cash, Yen, Bank)

-- | The deposit is held at Bank A.
depositBase :: (AccountTitles, Unit, Bank)
depositBase = (Deposits, Yen, BankA)

Use these bases in the two terms of the withdrawal.

-- | The withdrawal using bases with a bank element.
bankWithdrawal :: Alg MoneyDecimal (HatBase (AccountTitles, Unit, Bank))
bankWithdrawal = 3000 .@ Not :< cashBase
              .+ 3000 .@ Hat :< depositBase

Query bases by their elements

In a query, (.#) stands for the wildcard of the inferred element type. Use it to leave the bank unrestricted. Import matchesQuery to compare a query directly with a stored base.

import ExchangeAlgebra.Algebra.Element (matchesQuery)
-- | Select terms on accounts at Bank A.
bankATerms :: Alg MoneyDecimal (HatBase (AccountTitles, Unit, Bank))
bankATerms = proj [HatNot :< ((.#), (.#), BankA)] bankWithdrawal

-- | Check the cash base with an unrestricted or a specific bank query.
cashMatchesAnyBank, cashMatchesBankA :: Bool
cashMatchesAnyBank = matchesQuery (Cash, Yen, (.#)) cashBase
cashMatchesBankA = matchesQuery (Cash, Yen, BankA) cashBase

The projection selects the deposit term at Bank A. The cash base matches the unrestricted bank query. A query for the specific value BankA skips that cash base because its bank element is the stored wildcard.

Save the complete program as Main.hs, then use the commands in Run the program.

Complete program

{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}

module Main where

import ExchangeAlgebra hiding (Yen, Dollar)
import ExchangeAlgebra.Algebra.Element (matchesQuery)

data Unit = Yen | Dollar | Unit
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Element Unit where
    wildcard = Unit

-- | The bank where a deposit is held.
data Bank = BankA | BankB | Bank
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Element Bank where
    wildcard = Bank

-- | Cash has no applicable bank.
cashBase :: (AccountTitles, Unit, Bank)
cashBase = (Cash, Yen, Bank)

-- | The deposit is held at Bank A.
depositBase :: (AccountTitles, Unit, Bank)
depositBase = (Deposits, Yen, BankA)

-- | The withdrawal using bases with a bank element.
bankWithdrawal :: Alg MoneyDecimal (HatBase (AccountTitles, Unit, Bank))
bankWithdrawal = 3000 .@ Not :< cashBase
              .+ 3000 .@ Hat :< depositBase

-- | Select terms on accounts at Bank A.
bankATerms :: Alg MoneyDecimal (HatBase (AccountTitles, Unit, Bank))
bankATerms = proj [HatNot :< ((.#), (.#), BankA)] bankWithdrawal

-- | Check the cash base with an unrestricted or a specific bank query.
cashMatchesAnyBank, cashMatchesBankA :: Bool
cashMatchesAnyBank = matchesQuery (Cash, Yen, (.#)) cashBase
cashMatchesBankA = matchesQuery (Cash, Yen, BankA) cashBase

-- | Print a result with the question or operation that produced it.
printNamed :: Show a => String -> a -> IO ()
printNamed label value = putStrLn (label ++ ": " ++ show value)

-- | Print the deposit terms selected by bank and the cash base checks.
main :: IO ()
main = do
    printNamed "Bank A terms" bankATerms
    printNamed "Any-bank cash query matches cash without a bank" cashMatchesAnyBank
    printNamed "Bank A cash query matches cash without a bank" cashMatchesBankA

The program prints the results below.

Bank A terms: 3000:@Hat:<(Deposits,Yen,BankA)
Any-bank cash query matches cash without a bank: True
Bank A cash query matches cash without a bank: False

Tested with exchangealgebra-0.6.1.1 on 2026-11-23.

Query a date stored as an ordinary element

Wild a adds the wildcard Wild to the element type a. Wrap an ordinary element x in Exactly x.

Wrap the date 1858-11-17 in Exactly to store it in a cash term.

-- | Record a cash increase on 1858-11-17.
record :: Alg MoneyDecimal (HatBase (AccountTitles, Wild Day))
record = 100 .@ Not :< (Cash, Exactly (ModifiedJulianDay 0))
main :: IO ()
main = do
    putStrLn $ "Recorded term: " ++ show record
    putStrLn $ "Any date: " ++ show (norm (proj [HatNot :< (Cash, Wild)] record))
    putStrLn $ "1858-11-17: "
        ++ show (norm (proj [HatNot :< (Cash, Exactly (ModifiedJulianDay 0))] record))
    putStrLn $ "1858-11-18: "
        ++ show (norm (proj [HatNot :< (Cash, Exactly (ModifiedJulianDay 1))] record))

Save the complete program as Main.hs.

Complete program

module Main where

import Data.Time.Calendar (Day (ModifiedJulianDay))
import ExchangeAlgebra

-- | Record a cash increase on 1858-11-17.
record :: Alg MoneyDecimal (HatBase (AccountTitles, Wild Day))
record = 100 .@ Not :< (Cash, Exactly (ModifiedJulianDay 0))

main :: IO ()
main = do
    putStrLn $ "Recorded term: " ++ show record
    putStrLn $ "Any date: " ++ show (norm (proj [HatNot :< (Cash, Wild)] record))
    putStrLn $ "1858-11-17: "
        ++ show (norm (proj [HatNot :< (Cash, Exactly (ModifiedJulianDay 0))] record))
    putStrLn $ "1858-11-18: "
        ++ show (norm (proj [HatNot :< (Cash, Exactly (ModifiedJulianDay 1))] record))

Add time to your project’s dependencies. From the project directory, run stack exec -- ghc -Wall -Werror -package time Main.hs -o wild-day, then run ./wild-day.

Recorded term: 100:@Not:<(Cash,Exactly 1858-11-17)
Any date: 100
1858-11-17: 100
1858-11-18: 0

The Wild query selects the term. An Exactly query selects the term only when its date matches.

Tested with exchangealgebra-0.6.1.1 on 2026-11-20.

Reference

Element methods

Element requires Eq, Ord, Show, Hashable, and Typeable. Equality and ordering must agree, and equal values must have equal hashes. Identity and ordering treat the wildcard as an ordinary value. The derived order for Bank is BankA < BankB < Bank.

Method or functionMeaning
wildcard, or the alias (.#)The distinguished wildcard value of the inferred type.
isWildcard xWhether x equals the whole wildcard value.
haveWildcard xWhether x contains a wildcard element, including inside a tuple.
ignoreWildcard before afterUse each element of after unless it is a wildcard, in which case keep the corresponding element of before.
equal, (.==), (./=)Symmetric wildcard-aware comparison and its negation. (.==) also handles partially wildcarded tuples.
compareElementReturn EQ for a wildcard match, otherwise compare with the ordinary order. Compare tuples element by element.
(.<), (.>), (.<=), (.>=), maxElement, minElementComparisons and selection using compareElement.
matchesQuery query entryOne-way query matching. Import it from ExchangeAlgebra.Algebra.Element.

wildcard is the only required method for a simple element type. Tuples implement wildcard substitution and matching component by component. In a transfer target, a wildcard preserves the source element.

Caution: (.==) is symmetric. Use matchesQuery to match queries against stored elements or bases. Use ordinary == and compare for identity and canonical ordering; wildcard-aware comparison is not a total order on stored values.

Built-in instances

TypeWildcard
AccountTitlesAccountTitle. Import the account type from ExchangeAlgebra or ExchangeAlgebra.Accounting.Account.
CountUnitCountUnit; other constructors are Yen, Dollar, Euro, CNY, Amount.
TextThe empty text. Name and Subject are aliases for Text. You can use Subject to identify which accounting entity a record belongs to.
DayModifiedJulianDay 0 (1858-11-17). To use that date as an ordinary element, use Wild Day.
TimeOfDaymidnight (00:00). To use 00:00 as an ordinary element, use Wild TimeOfDay.
Wild aWild. Each value x of a is the ordinary element Exactly x. Added in 0.6.1.0.
Tuples of 2 through 7 element typesA tuple in which every element is a wildcard.
HatHatNot, for direction patterns.
HatBase a, for BaseClass aHatNot :< wildcard.
BaseForSingleHatIts sole constructor, BaseForSingleHat, used by the bare Hat base.

Int, Integer, Double, and String require a wrapper to serve as element types in 0.6.1.1. Use Wild to give each type a wildcard.

Wild a has Element and BaseClass instances when a has Ord, Show, Hashable, and Typeable instances. It derives Eq, Ord, Show, and Generic, and has NFData, Hashable, and Binary instances when a has the corresponding instance.

For example, Wild Int can identify branches by number. Int has no Element instance, so a base that contains Int without Wild does not compile. A query for Exactly 1 selects branch 1, and a query for Wild selects every branch:

-- | Cash at branches 1 and 2.
branches :: Alg MoneyDecimal (HatBase (AccountTitles, Wild Int))
branches = 100 .@ Not :< (Cash, Exactly 1)
        .+ 200 .@ Not :< (Cash, Exactly 2)

-- | Total the cash at branch 1 and at any branch.
branchQueries :: IO ()
branchQueries = do
    putStrLn $ "Branch 1: " ++ show (norm (proj [HatNot :< (Cash, Exactly 1)] branches))
    putStrLn $ "Any branch: " ++ show (norm (proj [HatNot :< (Cash, Wild)] branches))
Branch 1: 100
Any branch: 300

The Element instance for TimeOfDay uses 00:00 as its wildcard. A query for 00:00 therefore matches every time of day. A term stored at 00:00 means that no time of day applies, so a query for a specific time, such as 13:00, does not match it.

The following record receives cash at 00:00 and at 13:00 with TimeOfDay. The query for 00:00 selects both terms, and the query for 13:00 selects only the term at 13:00:

-- | Cash received at 00:00 and at 13:00, with the time as TimeOfDay.
byTime :: Alg MoneyDecimal (HatBase (AccountTitles, TimeOfDay))
byTime = 100 .@ Not :< (Cash, midnight)
      .+ 200 .@ Not :< (Cash, TimeOfDay 13 0 0)

-- | Total the cash selected by a query for 00:00 and by a query for 13:00.
timeQueries :: IO ()
timeQueries = do
    putStrLn $ "TimeOfDay, query 00:00: " ++ show (norm (proj [HatNot :< (Cash, midnight)] byTime))
    putStrLn $ "TimeOfDay, query 13:00: "
        ++ show (norm (proj [HatNot :< (Cash, TimeOfDay 13 0 0)] byTime))
TimeOfDay, query 00:00: 300
TimeOfDay, query 13:00: 200

To record 00:00 as an ordinary time, use Wild TimeOfDay, added in 0.6.1.0. Store Exactly midnight, and query Exactly midnight to select only 00:00 or Wild to select any time. Day and Wild Day treat 1858-11-17 in the same way. The built-in base (AccountTitles, Name, CountUnit, Subject, Wild Day, Wild TimeOfDay) has an ExBaseClass instance; see Built-in exchange bases.

With Wild TimeOfDay, the same receipts are distinguished by time:

-- | The same receipts, with the time as Wild TimeOfDay.
byWildTime :: Alg MoneyDecimal (HatBase (AccountTitles, Wild TimeOfDay))
byWildTime = 100 .@ Not :< (Cash, Exactly midnight)
          .+ 200 .@ Not :< (Cash, Exactly (TimeOfDay 13 0 0))

-- | Total the cash at 00:00, at 13:00, and at any time.
wildTimeQueries :: IO ()
wildTimeQueries = do
    putStrLn $ "Wild TimeOfDay, query Exactly 00:00: "
        ++ show (norm (proj [HatNot :< (Cash, Exactly midnight)] byWildTime))
    putStrLn $ "Wild TimeOfDay, query Exactly 13:00: "
        ++ show (norm (proj [HatNot :< (Cash, Exactly (TimeOfDay 13 0 0))] byWildTime))
    putStrLn $ "Wild TimeOfDay, query Wild: "
        ++ show (norm (proj [HatNot :< (Cash, Wild)] byWildTime))
Wild TimeOfDay, query Exactly 00:00: 100
Wild TimeOfDay, query Exactly 13:00: 200
Wild TimeOfDay, query Wild: 300

The query for Exactly midnight selects only the term at 00:00. For dates, Query a date stored as an ordinary element shows the same use of Wild Day.

These excerpts come from one program. To run it, save the complete program below as Main.hs and add time to your project’s dependencies. From the project directory, run stack exec -- ghc -Wall -Werror -package time Main.hs -o wild-elements, then run ./wild-elements.

Complete program

module Main where

import Data.Time.LocalTime (TimeOfDay (TimeOfDay), midnight)
import ExchangeAlgebra

-- | Cash at branches 1 and 2.
branches :: Alg MoneyDecimal (HatBase (AccountTitles, Wild Int))
branches = 100 .@ Not :< (Cash, Exactly 1)
        .+ 200 .@ Not :< (Cash, Exactly 2)

-- | Total the cash at branch 1 and at any branch.
branchQueries :: IO ()
branchQueries = do
    putStrLn $ "Branch 1: " ++ show (norm (proj [HatNot :< (Cash, Exactly 1)] branches))
    putStrLn $ "Any branch: " ++ show (norm (proj [HatNot :< (Cash, Wild)] branches))

-- | Cash received at 00:00 and at 13:00, with the time as TimeOfDay.
byTime :: Alg MoneyDecimal (HatBase (AccountTitles, TimeOfDay))
byTime = 100 .@ Not :< (Cash, midnight)
      .+ 200 .@ Not :< (Cash, TimeOfDay 13 0 0)

-- | Total the cash selected by a query for 00:00 and by a query for 13:00.
timeQueries :: IO ()
timeQueries = do
    putStrLn $ "TimeOfDay, query 00:00: " ++ show (norm (proj [HatNot :< (Cash, midnight)] byTime))
    putStrLn $ "TimeOfDay, query 13:00: "
        ++ show (norm (proj [HatNot :< (Cash, TimeOfDay 13 0 0)] byTime))

-- | The same receipts, with the time as Wild TimeOfDay.
byWildTime :: Alg MoneyDecimal (HatBase (AccountTitles, Wild TimeOfDay))
byWildTime = 100 .@ Not :< (Cash, Exactly midnight)
          .+ 200 .@ Not :< (Cash, Exactly (TimeOfDay 13 0 0))

-- | Total the cash at 00:00, at 13:00, and at any time.
wildTimeQueries :: IO ()
wildTimeQueries = do
    putStrLn $ "Wild TimeOfDay, query Exactly 00:00: "
        ++ show (norm (proj [HatNot :< (Cash, Exactly midnight)] byWildTime))
    putStrLn $ "Wild TimeOfDay, query Exactly 13:00: "
        ++ show (norm (proj [HatNot :< (Cash, Exactly (TimeOfDay 13 0 0))] byWildTime))
    putStrLn $ "Wild TimeOfDay, query Wild: "
        ++ show (norm (proj [HatNot :< (Cash, Wild)] byWildTime))

main :: IO ()
main = do
    branchQueries
    timeQueries
    wildTimeQueries

Tested with exchangealgebra-0.6.1.1 on 2026-11-23.

Bases

Change the base in Record a withdrawal to include the bank element. The base type determines which elements identify each term and which elements a query can match.

Add an element to the base

Use the triple (AccountTitles, Unit, Bank) as the underlying base and pair it with a direction using (:<). These two types implement Definition 2 and Definition 3.

-- | Cash increases with no applicable bank.
cashIncrease :: HatBase (AccountTitles, Unit, Bank)
cashIncrease = Not :< (Cash, Yen, Bank)

-- | Deposits at Bank A decrease.
depositDecrease :: HatBase (AccountTitles, Unit, Bank)
depositDecrease = Hat :< (Deposits, Yen, BankA)

The library supplies BaseClass for this triple because all three types have Element instances. It also supplies HatBaseClass for the resulting HatBase.

Declare the base instance

Update ExBaseClass to read and replace the first element of the triple. Keep the direction, unit, and bank when replacing the account title.

-- | Read or replace the title in a base that includes a bank.
instance ExBaseClass (HatBase (AccountTitles, Unit, Bank)) where
    getAccountTitle (_ :< (account, _, _)) = account
    setAccountTitle (direction :< (_, unit, bank)) account = direction :< (account, unit, bank)

FlexibleInstances permits this instance head. Implement getAccountTitle and setAccountTitle for a custom exchange base. The other methods have defaults based on the account title and direction, and the Exchange instance for Alg uses them.

Built-in exchange bases

In 0.6.1.1, the following forms of HatBase a have built-in ExBaseClass instances.

a in HatBase a
AccountTitles
(AccountTitles, Day)
(AccountTitles, Name)
(CountUnit, AccountTitles)
(AccountTitles, Name, CountUnit)
(AccountTitles, Name, CountUnit, Subject)
(AccountTitles, Name, CountUnit, Subject, Day)
(AccountTitles, Name, CountUnit, Subject, Day, TimeOfDay)
(AccountTitles, Wild Day)
(AccountTitles, Name, CountUnit, Subject, Wild Day)
(AccountTitles, Name, CountUnit, Subject, Wild Day, Wild TimeOfDay)

Use a single unit as a base

To use Unit itself as the underlying base, declare BaseClass Unit. The empty instance uses the default compareBase implementation. The resulting HatBase Unit can identify an amount in yen without an account title.

-- | Permit Unit itself, as well as tuples containing it, to be a base.
instance BaseClass Unit where

-- | A base with one element, used to compare the instance requirements.
yenOnly :: HatBase Unit
yenOnly = Not :< Yen

Inspect the withdrawal bases

Use base and hat to read the elements and direction. revHat reverses the cash direction and leaves (Cash, Yen, Bank) intact. merge reconstructs the deposit hat base from the direction and elements. Replacing Deposits with Cash through setAccountTitle preserves Hat, Yen, and BankA in the example.

-- | Inspect the direction, account, unit, and bank of the example bases.
main :: IO ()
main = do
    printNamed "Cash increase" cashIncrease
    printNamed "Deposit decrease" depositDecrease
    printNamed "Elements of the cash increase" (base cashIncrease)
    printNamed "Direction of the deposit change" (hat depositDecrease)
    printNamed "Reverse the cash direction" (revHat cashIncrease)
    printNamed "Rebuild the deposit decrease"
        (merge (hat depositDecrease) (base depositDecrease) :: HatBase (AccountTitles, Unit, Bank))
    printNamed "Replace the account title" (setAccountTitle depositDecrease Cash)
    printNamed "Single-element yen base" yenOnly

Save the complete program as Main.hs, then use the commands in Run the program.

Complete program

{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}

module Main where

import ExchangeAlgebra hiding (Yen, Dollar)

data Unit = Yen | Dollar | Unit
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Element Unit where
    wildcard = Unit

-- | The bank where a deposit is held.
data Bank = BankA | BankB | Bank
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Element Bank where
    wildcard = Bank

-- | Cash increases with no applicable bank.
cashIncrease :: HatBase (AccountTitles, Unit, Bank)
cashIncrease = Not :< (Cash, Yen, Bank)

-- | Deposits at Bank A decrease.
depositDecrease :: HatBase (AccountTitles, Unit, Bank)
depositDecrease = Hat :< (Deposits, Yen, BankA)

-- | Read or replace the title in a base that includes a bank.
instance ExBaseClass (HatBase (AccountTitles, Unit, Bank)) where
    getAccountTitle (_ :< (account, _, _)) = account
    setAccountTitle (direction :< (_, unit, bank)) account = direction :< (account, unit, bank)

-- | Permit Unit itself, as well as tuples containing it, to be a base.
instance BaseClass Unit where

-- | A base with one element, used to compare the instance requirements.
yenOnly :: HatBase Unit
yenOnly = Not :< Yen

-- | Print a result with the question or operation that produced it.
printNamed :: Show a => String -> a -> IO ()
printNamed label value = putStrLn (label ++ ": " ++ show value)

-- | Inspect the direction, account, unit, and bank of the example bases.
main :: IO ()
main = do
    printNamed "Cash increase" cashIncrease
    printNamed "Deposit decrease" depositDecrease
    printNamed "Elements of the cash increase" (base cashIncrease)
    printNamed "Direction of the deposit change" (hat depositDecrease)
    printNamed "Reverse the cash direction" (revHat cashIncrease)
    printNamed "Rebuild the deposit decrease"
        (merge (hat depositDecrease) (base depositDecrease) :: HatBase (AccountTitles, Unit, Bank))
    printNamed "Replace the account title" (setAccountTitle depositDecrease Cash)
    printNamed "Single-element yen base" yenOnly
Cash increase: Not:<(Cash,Yen,Bank)
Deposit decrease: Hat:<(Deposits,Yen,BankA)
Elements of the cash increase: (Cash,Yen,Bank)
Direction of the deposit change: Hat
Reverse the cash direction: Hat:<(Cash,Yen,Bank)
Rebuild the deposit decrease: Hat:<(Deposits,Yen,BankA)
Replace the account title: Hat:<(Cash,Yen,BankA)
Single-element yen base: Not:<Yen

Caution: Hat represents a direction on a nonnegative amount. The account and direction together determine the debit or credit side. Use HatNot in query patterns. Some direction tests and reversal methods fail on HatNot.

Tested with exchangealgebra-0.6.1.1 on 2026-11-23.

Reference

BaseClass

BaseClass a requires Element a and provides compareBase :: a -> a -> Ordering, defaulting to compareElement. Built-in base types with a single element include AccountTitles, CountUnit, Text (also called Name), Day, TimeOfDay, and Wild a when a has Ord, Show, Hashable, and Typeable instances. Tuples of 2 through 7 element types have BaseClass instances even when individual element types have no separate BaseClass instance.

HatBaseClass

HatBaseClass requires BaseClass for both the whole hat base and its BasePart, and AxisDecompose for BasePart. AxisDecompose supplies a key for each element of the base. Its generic and tuple instances cover the bases used in the withdrawal.

Associated type or methodPurpose
BasePart aThe base type after removing the direction. For HatBase a, this is a.
base, hatExtract the underlying base and direction.
mergeBuild a hat base from a direction and a base part.
toHat, toNotSet the direction while retaining the base.
revHatExchange Hat and Not.
isHat, isNotTest the direction.
compareHatBaseCompare hat bases; its default is compareBase.

A custom representation must implement BasePart, base, hat, merge, toHat, toNot, revHat, isHat, and isNot. Reconstruction must preserve the underlying base and direction. Reversing twice must restore a concrete base. HatBase a already implements these operations. The bare Hat type has an instance with the single-value BaseForSingleHat as its base part.

Redundant and exchange algebras

Compare amount types, work with a month’s terms, and read debit and credit differences. The examples use exchangealgebra-0.6.1.1 and keep the account-and-unit base from Record a withdrawal.

Amount types

Choose an amount type

Keep MoneyDecimal when you need exact decimal amounts. Its decimal arithmetic represents 3,000 yen and the sum of the term amounts exactly. Axioms 4 and 5 hold exactly when the amounts, intermediate sums, and products are representable. The numerical conditions on the axioms distinguish exact arithmetic from a rounded readout.

MoneyDecimal has an integer mantissa and a scale of up to 255 decimal places. A product is exact when representable; division can require rounding. bankersRound explicitly rounds to a chosen number of decimal places, with ties to even, when a monetary amount must be finalized.

Build the entry with withdrawalWithAmount. Both terms use the amount type of its argument.

-- | Build the entry with the chosen nonnegative amount of each term.
withdrawalWithAmount :: HatVal amount => amount -> Alg amount (HatBase (AccountTitles, Unit))
withdrawalWithAmount amount = amount .@ Not :< (Cash, Yen)
                           .+ amount .@ Hat :< (Deposits, Yen)

MoneyDouble wraps binary floating-point Double. Give the entry the amount type MoneyDouble to compare binary and decimal arithmetic on the same terms.

-- | The same withdrawal with binary floating-point amounts.
doubleWithdrawal :: Alg MoneyDouble (HatBase (AccountTitles, Unit))
doubleWithdrawal = withdrawalWithAmount 3000

Compare portions of the withdrawal

Scale the entry by 10% and 20%. The code compares adding the two scaled entries with adding the ratios before scaling.

-- | Compare separate 10% and 20% portions with one combined 30% portion.
decimalPortions :: (MoneyDecimal, MoneyDecimal)
decimalPortions = ( norm (0.1 .* withdrawal .+ 0.2 .* withdrawal)
                  , norm ((0.1 + 0.2) .* withdrawal))

-- | Binary rounding can distinguish the two constructions of the portions.
doublePortions :: (MoneyDouble, MoneyDouble)
doublePortions = ( norm (0.1 .* doubleWithdrawal .+ 0.2 .* doubleWithdrawal)
                 , norm ((0.1 + 0.2) .* doubleWithdrawal))
-- | Compare decimal and binary results of fractional scaling.
printPortions :: IO ()
printPortions = do
    printNamed "Decimal portion totals (separate, combined)" decimalPortions
    printNamed "Binary portion totals (separate, combined)" doublePortions
Decimal portion totals (separate, combined): (1800,1800)
Binary portion totals (separate, combined): (1800.0,1800.0000000000002)

The decimal calculations agree. In binary arithmetic, 0.1 + 0.2 rounds before multiplication. Both totals count the cash and deposit terms, so the 30% portion counts 1,800 yen across both terms and 900 yen on the cash term alone. For finite stored amounts, norm sums exactly in an accumulator and rounds once. Each stored amount already includes any rounding from its construction or scaling.

Construction and scalar checks

The value types, including MoneyDecimal, can represent negative numbers. The constructor .@ rejects negative or non-finite term amounts. It checks the direction first and rejects HatNot even for zero; a zero amount with a concrete direction gives Zero.

For scalar multiplication, any scalar times Zero gives Zero, and a zero scalar times an algebra gives Zero. These shortcuts are processed before scalar validation. A negative or non-finite scalar applied to a nonzero algebra raises error. Finite floating-point inputs do not guarantee finite products.

Run the amount checks

Catch the documented construction errors in the example so that the program can report every check:

import Control.Exception (ErrorCall, evaluate, try)
-- | Report whether construction raises the documented ErrorCall.
rejectsTerm :: Alg MoneyDouble (HatBase (AccountTitles, Unit)) -> IO Bool
rejectsTerm expression = do
    result <- try (evaluate expression)
        :: IO (Either ErrorCall (Alg MoneyDouble (HatBase (AccountTitles, Unit))))
    pure $ case result of
        Left _  -> True
        Right _ -> False
-- | Check invalid amounts, directions, and scalars.
printChecks :: IO ()
printChecks = do
    rejectsTerm ((-3000) .@ Not :< (Cash, Yen)) >>= printNamed "Negative amount rejected"
    rejectsTerm ((1 / 0) .@ Not :< (Cash, Yen)) >>= printNamed "Infinite amount rejected"
    rejectsTerm ((0 / 0) .@ Not :< (Cash, Yen)) >>= printNamed "NaN amount rejected"
    rejectsTerm (0 .@ HatNot :< (Cash, Yen)) >>= printNamed "Wildcard side rejected"
    rejectsTerm ((-1) .* doubleWithdrawal) >>= printNamed "Negative scalar rejected"
    rejectsTerm ((1 / 0) .* doubleWithdrawal) >>= printNamed "Infinite scalar rejected"
    rejectsTerm ((0 / 0) .* doubleWithdrawal) >>= printNamed "NaN scalar rejected"
    printNamed "Negative scalar times Zero"
        ((-1) .* (Zero :: Alg MoneyDouble (HatBase (AccountTitles, Unit))))
    printNamed "Zero scalar times withdrawal" (0 .* doubleWithdrawal)
Negative amount rejected: True
Infinite amount rejected: True
NaN amount rejected: True
Wildcard side rejected: True
Negative scalar rejected: True
Infinite scalar rejected: True
NaN scalar rejected: True
Negative scalar times Zero: 0
Zero scalar times withdrawal: 0

Application code must validate external amounts before constructing terms.

Declare a custom yen amount type

A custom value type requires its own validation and accumulator operations. YenAmount represents rational yen amounts, so even a fractional allocation such as one seventh is exact. The accumulator can hold signed differences internally, while negative values remain invalid as terms. The default postingUpperBound is appropriate because rational amounts have no magnitude bound and no NaN or infinities.

-- | Yen amounts with exact rational arithmetic; negative values cannot be posted.
newtype YenAmount = YenAmount Rational
    deriving stock (Eq, Ord, Show)
    deriving newtype (Num, Fractional, Real)

instance Nearly YenAmount where
    isNearly = isNearlyNum

-- The accumulator may be signed even though terms must be nonnegative.
instance HatVal YenAmount where
    zeroValue = 0

    valueError (YenAmount amount)
        | amount < 0 = Just NegativeValue
        | otherwise  = Nothing

    showValue (YenAmount amount) = show amount

    newtype Accum YenAmount = YenAccum Rational

    emptyAccum = YenAccum 0
    addAccum (YenAmount amount) (YenAccum total) = YenAccum (amount + total)
    mergeAccum (YenAccum left) (YenAccum right) = YenAccum (left + right)
    negateAccum (YenAccum total) = YenAccum (negate total)
    signAccum (YenAccum total) = Just (compare total 0)
    roundAccum (YenAccum total) = YenAmount total

    splitAccum (YenAccum total)
        | total > 0 = Just [YenAmount total]
        | otherwise = Nothing

    exactAccum (YenAccum total) = Just total
    roundRational Nearest amount = Just (YenAmount amount)
    roundRational (ToMultipleOf (YenAmount unit)) amount
        | unit > 0 = Just (YenAmount (unit * fromInteger (round (amount / unit))))
        | otherwise = Nothing
-- | Print the entry with rational yen amounts.
printRationalWithdrawal :: IO ()
printRationalWithdrawal =
    printNamed "Rational yen withdrawal"
        (withdrawalWithAmount 3000 :: Alg YenAmount (HatBase (AccountTitles, Unit)))
Rational yen withdrawal: 3000 % 1:@Not:<(Cash,Yen) .+ 3000 % 1:@Hat:<(Deposits,Yen)

Operations

The operations of Definition 6 apply to each term or full base as specified. For example, norm withdrawal counts both terms and gives 6,000 yen. 2 .* withdrawal doubles each term while keeping its base and direction.

Add the month’s transactions

Suppose the business withdraws another 2,000 yen on January 15, buys goods for 500 yen in cash on January 20, and exchanges 1,500 yen in cash for 10 dollars on January 25. The exchange has no fee and uses 150 yen per dollar. Record each transaction and add it to the month:

-- | January 15: withdraw another 2,000 yen.
secondWithdrawal :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
secondWithdrawal = 2000 .@ Not :< (Cash, Yen)
                .+ 2000 .@ Hat :< (Deposits, Yen)

-- | January 20: buy goods for 500 yen in cash, recorded as Purchases.
cashPayment :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
cashPayment = 500 .@ Hat :< (Cash, Yen)
           .+ 500 .@ Not :< (Purchases, Yen)

-- | January 25: exchange 1,500 yen in cash for 10 dollars, with no fee.
currencyExchange :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
currencyExchange = 1500 .@ Hat :< (Cash, Yen)
                .+   10 .@ Not :< (Cash, Dollar)

-- | Changes recorded during the month, with no opening balances.
month :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
month = withdrawal .+ secondWithdrawal .+ cashPayment .+ currencyExchange

month contains the recorded changes without opening balances. Adding the withdrawals with .+ retains the cash increases of 3,000 and 2,000 as separate amounts on (Cash, Yen). The cash payment and currency exchange also retain separate decreases on that base. No implicit sum or cancellation occurs at a shared base.

The payment uses Purchases for the goods purchased. The exchange reduces yen cash and increases dollar cash; the two currencies remain distinct currency elements.

Select an operation

What cash remains in each currency? Apply bar to net the changes within each full base, then proj to select Cash without restricting the unit. The yen cash change is 3,000 + 2,000 - 500 - 1,500 = 3,000 yen, and the dollar cash change is 10 dollars. These are balances of the recorded changes; the yen deposit decrease also requires an opening balance to determine the deposit still held.

What is the total of the yen terms? Select all yen bases with proj, then apply norm. This measures gross amounts in those terms, counting both directions and both accounts of the withdrawals. It is not a net cash flow. Select a unit before totaling: adding yen and dollar amounts without conversion does not produce a monetary total in either currency.

Which cash changes were recorded in yen? Select (Cash, Yen) without applying bar. The original term amounts remain available in the selected algebra.

-- | Remaining cash by currency after canceling changes within each full base.
cashBalances :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
cashBalances = proj [HatNot :< (Cash, (.#))] (bar month)

-- | Original yen terms on every account and in both directions.
yenTerms :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
yenTerms = proj [HatNot :< ((.#), Yen)] month

-- | Original cash terms in yen, before aggregation.
yenCashTerms :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
yenCashTerms = proj [HatNot :< (Cash, Yen)] month

The query HatNot :< (Cash, (.#)) restricts the account but leaves direction and currency unrestricted. HatNot :< ((.#), Yen) restricts the currency but leaves account and direction unrestricted. A query wildcard matches any stored element. A concrete query element matches only an equal stored element, as in Query bases by their elements.

What are the cash increases and decreases separately? compress yenCashTerms totals each direction independently. It gives an increase total of 5,000 yen and a decrease total of 2,000 yen. bar instead cancels the totals and leaves the increase of 3,000 yen. Both operations explicitly discard individual term detail.

What reverses the withdrawal? (.^) withdrawal changes the cash increase into a decrease and the deposit decrease into an increase. Every amount remains 3,000. Adding this value to withdrawal keeps both sets of terms; applying bar to the sum gives zero. Applying hat twice restores the original directions.

Run the queries

Print each answer with the question or operation that produced it:

-- | Print scaling, projection, netting, and reversal results.
printOperations :: IO ()
printOperations = do
    printNamed "Twice the withdrawal" (2 .* withdrawal)
    printNamed "Withdrawal term total in yen" (norm withdrawal)
    printNamed "Yen cash terms before aggregation" yenCashTerms
    printNamed "Cash balances by currency" cashBalances
    printNamed "Yen terms without cancellation" yenTerms
    printNamed "Yen term total" (norm yenTerms)
    printNamed "Yen cash totals by direction" (compress yenCashTerms)
    printNamed "Yen cash residual amount" (projNetNorm [HatNot :< (Cash, Yen)] month)
    printNamed "Reverse the withdrawal directions" ((.^) withdrawal)
    printNamed "Withdrawal plus its hat, before bar" (withdrawal .+ (.^) withdrawal)
    printNamed "Withdrawal plus its hat, after bar" (bar (withdrawal .+ (.^) withdrawal))

The program prints:

Twice the withdrawal: 6000:@Not:<(Cash,Yen) .+ 6000:@Hat:<(Deposits,Yen)
Withdrawal term total in yen: 6000
Yen cash terms before aggregation: 500:@Hat:<(Cash,Yen) .+ 1500:@Hat:<(Cash,Yen) .+ 2000:@Not:<(Cash,Yen) .+ 3000:@Not:<(Cash,Yen)
Cash balances by currency: 3000:@Not:<(Cash,Yen) .+ 10:@Not:<(Cash,Dollar)
Yen terms without cancellation: 500:@Hat:<(Cash,Yen) .+ 1500:@Hat:<(Cash,Yen) .+ 2000:@Not:<(Cash,Yen) .+ 3000:@Not:<(Cash,Yen) .+ 2000:@Hat:<(Deposits,Yen) .+ 3000:@Hat:<(Deposits,Yen) .+ 500:@Not:<(Purchases,Yen)
Yen term total: 12500
Yen cash totals by direction: 2000:@Hat:<(Cash,Yen) .+ 5000:@Not:<(Cash,Yen)
Yen cash residual amount: 3000
Reverse the withdrawal directions: 3000:@Hat:<(Cash,Yen) .+ 3000:@Not:<(Deposits,Yen)
Withdrawal plus its hat, before bar: 3000:@Hat:<(Cash,Yen) .+ 3000:@Not:<(Cash,Yen) .+ 3000:@Hat:<(Deposits,Yen) .+ 3000:@Not:<(Deposits,Yen)
Withdrawal plus its hat, after bar: 0

Yen cash terms before aggregation retains the separate withdrawal and payment amounts. Cash balances by currency contains the net cash changes in yen and dollars, while Yen term total counts the gross yen amounts on every account. Yen cash totals by direction contains the separate increase and decrease totals. The named withdrawal-plus-hat results distinguish retaining opposing terms from canceling them with bar.

The displayed sequence order can differ from the source expression’s order. Construction routes can arrange the same terms differently, and structural Eq can observe that arrangement. Do not infer chronological order from the printed algebra. When comparing aggregated content, choose an explicit compress or bar according to whether the opposing directions must remain separate.

Exchange algebra

Read the debit and credit difference

Use diffRL to find the larger side and the difference. The function compares exact totals before rounding the difference once. It returns (Side, 0) when the totals agree, as they do for the withdrawal.

-- | Print each side's yen total and the difference rounded once.
printDifference :: IO ()
printDifference = do
    printNamed "Debit total in yen" (norm (decL withdrawal))
    printNamed "Credit total in yen" (norm (decR withdrawal))
    printNamed "Debit-credit difference" (diffRL withdrawal)
Debit total in yen: 3000
Credit total in yen: 3000
Debit-credit difference: (Side,0)

Classify an account and check its side

whatDiv gives the account division and whichSide uses both the account and the direction. whatPIMO gives the account’s role in an exchange, and fixedCurrent classifies the account as current, fixed, or other. The example classifies cash as PS (plus stock) and Current.

-- | Print account classifications and the sides of selected terms.
printClassification :: IO ()
printClassification = do
    printNamed "Cash division" (whatDiv (Not :< (Cash, Yen)))
    printNamed "Cash increase side" (whichSide (Not :< (Cash, Yen)))
    printNamed "Deposit decrease side" (whichSide (Hat :< (Deposits, Yen)))
    printNamed "Cash PIMO class" (whatPIMO (Not :< (Cash, Yen)))
    printNamed "Cash maturity class" (fixedCurrent (Not :< (Cash, Yen)))
Cash division: Assets
Cash increase side: Debit
Deposit decrease side: Credit
Cash PIMO class: PS
Cash maturity class: Current

See Account titles and their attributes for the registry fields behind these classifications.

Compare amounts in one currency

Select a single unit before calling diffRL or balance. For the month’s currency exchange, the yen terms have a credit excess of 1,500 yen and the dollar terms have a debit excess of 10 dollars. For a joint comparison, convert the amounts to one unit first.

-- | Read each currency's difference on its own.
printCurrencyDifferences :: IO ()
printCurrencyDifferences = do
    printNamed "Exchange difference in yen"
        (diffRL (proj [HatNot :< ((.#), Yen)] currencyExchange))
    printNamed "Exchange difference in dollars"
        (diffRL (proj [HatNot :< ((.#), Dollar)] currencyExchange))
Exchange difference in yen: (Credit,1500)
Exchange difference in dollars: (Debit,10)

Save the complete program as Main.hs, then use the commands in Run the program.

Complete program

{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE TypeFamilies #-}

module Main where

import ExchangeAlgebra hiding (Yen, Dollar)
import Control.Exception (ErrorCall, evaluate, try)

-- | Currency elements for the withdrawal.
data Unit
    = Yen
    | Dollar
    | Unit
    deriving stock (Eq, Ord, Show, Generic)
    deriving anyclass (Hashable)

instance Element Unit where
    wildcard = Unit

-- | Account access for the custom account-and-currency base.
instance ExBaseClass (HatBase (AccountTitles, Unit)) where
    getAccountTitle (_ :< (account, _)) = account
    setAccountTitle (direction :< (_, unit)) account = direction :< (account, unit)

-- | Build the entry with the chosen nonnegative amount of each term.
withdrawalWithAmount :: HatVal amount => amount -> Alg amount (HatBase (AccountTitles, Unit))
withdrawalWithAmount amount = amount .@ Not :< (Cash, Yen)
                           .+ amount .@ Hat :< (Deposits, Yen)

-- | The January 10 withdrawal with decimal amounts.
withdrawal :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
withdrawal = withdrawalWithAmount 3000

-- | The same withdrawal with binary floating-point amounts.
doubleWithdrawal :: Alg MoneyDouble (HatBase (AccountTitles, Unit))
doubleWithdrawal = withdrawalWithAmount 3000

-- | Compare separate 10% and 20% portions with one combined 30% portion.
decimalPortions :: (MoneyDecimal, MoneyDecimal)
decimalPortions = ( norm (0.1 .* withdrawal .+ 0.2 .* withdrawal)
                  , norm ((0.1 + 0.2) .* withdrawal))

-- | Binary rounding can distinguish the two constructions of the portions.
doublePortions :: (MoneyDouble, MoneyDouble)
doublePortions = ( norm (0.1 .* doubleWithdrawal .+ 0.2 .* doubleWithdrawal)
                 , norm ((0.1 + 0.2) .* doubleWithdrawal))

-- | Report whether construction raises the documented ErrorCall.
rejectsTerm :: Alg MoneyDouble (HatBase (AccountTitles, Unit)) -> IO Bool
rejectsTerm expression = do
    result <- try (evaluate expression)
        :: IO (Either ErrorCall (Alg MoneyDouble (HatBase (AccountTitles, Unit))))
    pure $ case result of
        Left _  -> True
        Right _ -> False

-- | Yen amounts with exact rational arithmetic; negative values cannot be posted.
newtype YenAmount = YenAmount Rational
    deriving stock (Eq, Ord, Show)
    deriving newtype (Num, Fractional, Real)

instance Nearly YenAmount where
    isNearly = isNearlyNum

-- The accumulator may be signed even though terms must be nonnegative.
instance HatVal YenAmount where
    zeroValue = 0

    valueError (YenAmount amount)
        | amount < 0 = Just NegativeValue
        | otherwise  = Nothing

    showValue (YenAmount amount) = show amount

    newtype Accum YenAmount = YenAccum Rational

    emptyAccum = YenAccum 0
    addAccum (YenAmount amount) (YenAccum total) = YenAccum (amount + total)
    mergeAccum (YenAccum left) (YenAccum right) = YenAccum (left + right)
    negateAccum (YenAccum total) = YenAccum (negate total)
    signAccum (YenAccum total) = Just (compare total 0)
    roundAccum (YenAccum total) = YenAmount total

    splitAccum (YenAccum total)
        | total > 0 = Just [YenAmount total]
        | otherwise = Nothing

    exactAccum (YenAccum total) = Just total
    roundRational Nearest amount = Just (YenAmount amount)
    roundRational (ToMultipleOf (YenAmount unit)) amount
        | unit > 0 = Just (YenAmount (unit * fromInteger (round (amount / unit))))
        | otherwise = Nothing

-- | January 15: withdraw another 2,000 yen.
secondWithdrawal :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
secondWithdrawal = 2000 .@ Not :< (Cash, Yen)
                .+ 2000 .@ Hat :< (Deposits, Yen)

-- | January 20: buy goods for 500 yen in cash, recorded as Purchases.
cashPayment :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
cashPayment = 500 .@ Hat :< (Cash, Yen)
           .+ 500 .@ Not :< (Purchases, Yen)

-- | January 25: exchange 1,500 yen in cash for 10 dollars, with no fee.
currencyExchange :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
currencyExchange = 1500 .@ Hat :< (Cash, Yen)
                .+   10 .@ Not :< (Cash, Dollar)

-- | Changes recorded during the month, with no opening balances.
month :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
month = withdrawal .+ secondWithdrawal .+ cashPayment .+ currencyExchange

-- | Remaining cash by currency after canceling changes within each full base.
cashBalances :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
cashBalances = proj [HatNot :< (Cash, (.#))] (bar month)

-- | Original yen terms on every account and in both directions.
yenTerms :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
yenTerms = proj [HatNot :< ((.#), Yen)] month

-- | Original cash terms in yen, before aggregation.
yenCashTerms :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
yenCashTerms = proj [HatNot :< (Cash, Yen)] month

-- | Print a result with the question or operation that produced it.
printNamed :: Show a => String -> a -> IO ()
printNamed label value = putStrLn (label ++ ": " ++ show value)

-- | Compare decimal and binary results of fractional scaling.
printPortions :: IO ()
printPortions = do
    printNamed "Decimal portion totals (separate, combined)" decimalPortions
    printNamed "Binary portion totals (separate, combined)" doublePortions

-- | Check invalid amounts, directions, and scalars.
printChecks :: IO ()
printChecks = do
    rejectsTerm ((-3000) .@ Not :< (Cash, Yen)) >>= printNamed "Negative amount rejected"
    rejectsTerm ((1 / 0) .@ Not :< (Cash, Yen)) >>= printNamed "Infinite amount rejected"
    rejectsTerm ((0 / 0) .@ Not :< (Cash, Yen)) >>= printNamed "NaN amount rejected"
    rejectsTerm (0 .@ HatNot :< (Cash, Yen)) >>= printNamed "Wildcard side rejected"
    rejectsTerm ((-1) .* doubleWithdrawal) >>= printNamed "Negative scalar rejected"
    rejectsTerm ((1 / 0) .* doubleWithdrawal) >>= printNamed "Infinite scalar rejected"
    rejectsTerm ((0 / 0) .* doubleWithdrawal) >>= printNamed "NaN scalar rejected"
    printNamed "Negative scalar times Zero"
        ((-1) .* (Zero :: Alg MoneyDouble (HatBase (AccountTitles, Unit))))
    printNamed "Zero scalar times withdrawal" (0 .* doubleWithdrawal)

-- | Print the entry with rational yen amounts.
printRationalWithdrawal :: IO ()
printRationalWithdrawal =
    printNamed "Rational yen withdrawal"
        (withdrawalWithAmount 3000 :: Alg YenAmount (HatBase (AccountTitles, Unit)))

-- | Print scaling, projection, netting, and reversal results.
printOperations :: IO ()
printOperations = do
    printNamed "Twice the withdrawal" (2 .* withdrawal)
    printNamed "Withdrawal term total in yen" (norm withdrawal)
    printNamed "Yen cash terms before aggregation" yenCashTerms
    printNamed "Cash balances by currency" cashBalances
    printNamed "Yen terms without cancellation" yenTerms
    printNamed "Yen term total" (norm yenTerms)
    printNamed "Yen cash totals by direction" (compress yenCashTerms)
    printNamed "Yen cash residual amount" (projNetNorm [HatNot :< (Cash, Yen)] month)
    printNamed "Reverse the withdrawal directions" ((.^) withdrawal)
    printNamed "Withdrawal plus its hat, before bar" (withdrawal .+ (.^) withdrawal)
    printNamed "Withdrawal plus its hat, after bar" (bar (withdrawal .+ (.^) withdrawal))

-- | Print each side's yen total and the difference rounded once.
printDifference :: IO ()
printDifference = do
    printNamed "Debit total in yen" (norm (decL withdrawal))
    printNamed "Credit total in yen" (norm (decR withdrawal))
    printNamed "Debit-credit difference" (diffRL withdrawal)

-- | Print account classifications and the sides of selected terms.
printClassification :: IO ()
printClassification = do
    printNamed "Cash division" (whatDiv (Not :< (Cash, Yen)))
    printNamed "Cash increase side" (whichSide (Not :< (Cash, Yen)))
    printNamed "Deposit decrease side" (whichSide (Hat :< (Deposits, Yen)))
    printNamed "Cash PIMO class" (whatPIMO (Not :< (Cash, Yen)))
    printNamed "Cash maturity class" (fixedCurrent (Not :< (Cash, Yen)))

-- | Read each currency's difference on its own.
printCurrencyDifferences :: IO ()
printCurrencyDifferences = do
    printNamed "Exchange difference in yen"
        (diffRL (proj [HatNot :< ((.#), Yen)] currencyExchange))
    printNamed "Exchange difference in dollars"
        (diffRL (proj [HatNot :< ((.#), Dollar)] currencyExchange))

-- | Run the amount, operation, and exchange examples in chapter order.
main :: IO ()
main = do
    printPortions
    printChecks
    printRationalWithdrawal
    printOperations
    printDifference
    printClassification
    printCurrencyDifferences

Tested with exchangealgebra-0.6.1.1 on 2026-11-23.

Reference

Amount types

HatVal methods and laws

HatVal requires Show, Ord, Eq, Nearly, Fractional, and Num. Built-in instances include MoneyDecimal, MoneyDouble, and bare Double.

MethodsPurpose
zeroValue, isZeroValueDefine zero and test it. isZeroValue has an equality-based default.
valueErrorReturn Nothing for a finite nonnegative value, Just NegativeValue for a negative finite value, or Just NonFiniteValue for NaN or either infinity.
postingUpperBoundAn optional bound used by checked term construction. Its default is Nothing; the floating-point instances use a bound of 2^900.
showValueRender an amount inside the algebra’s Show output. Decimal amounts retain decimal formatting; floating-point amounts use the instance’s formatting.
Associated data family Accum nRepresent an exact signed sum, including special states if the value type has NaN or infinities.
emptyAccum, addAccum, mergeAccum, negateAccumConstruct and combine exact sums and differences.
signAccum, roundAccum, exactAccumObserve the sign, round once to an amount, or read a finite sum as a Rational.
splitAccumSplit a positive exact sum into positive finite amounts with that same exact total. Return Nothing for nonpositive or non-finite states, or when the rounded total is infinite.
roundRationalConvert a rational using Nearest or ToMultipleOf unit, returning Nothing when the requested conversion is unavailable.

isErrorValue is derived from valueError; it is not a method to implement independently. An exact decimal instance returns Nothing for roundRational Nearest when the rational has no representable exact decimal value. Floating-point instances round to the nearest representable value and do not support ToMultipleOf.

An accumulator must merge associatively and commutatively with zero as its unit, preserve exact finite sums, and support exact subtraction through negation. Accumulating and rounding a single finite value must preserve that value. splitAccum must depend on the total, preserve it exactly, and succeed for every positive finite state with a finite rounded result. If the type represents NaN or infinities, accumulation of those values must follow IEEE addition. Value validation and ties-to-even rounding are also part of the instance contract.

Construction and operations

Alg requires a HatVal amount type and a HatBaseClass base type. Its Redundant instance implements the operations; defining a new element type does not require another Redundant instance. Zero is the empty algebra and the identity for addition. For value and direction checks, see Construction and scalar checks.

The public (:@) pattern matches a singleton term but cannot construct one in 0.6.1.1. Construct terms with .@. toList returns singleton terms, vals returns amounts, and bases returns hat bases.

OperationInputs and result
x .+ yRetain the terms from both algebras. Equal bases do not cause immediate summation or cancellation. (<>) is the same addition.
scalar .* xMultiply every amount by the scalar, preserving the term structure except for zero products. See Construction and scalar checks.
norm xTotal all stored amounts on both directions. Return an amount, losing base and direction information.
bar x, also written (.-) xTotal the opposing directions at each full base and keep only the excess on the winning direction. Remove an exactly canceled base.
compress xTotal each direction at each full base separately, without cancellation. This explicitly discards the separate terms within each direction.
(.^) xSwap Hat and Not for every term, preserving each amount.
proj patterns xSelect terms whose hat bases match at least one query pattern, without netting or changing amounts.
projNetNorm patterns xSelect bases, net within each full base, total the magnitudes of the residuals, and round once. Return an amount.

In 0.6.1.1, .* has the default fixity infixl 9, and .+ is infixr 3. Parenthesize mixed expressions to state the intended grouping, such as (2 .* withdrawal) .+ cashPayment.

Projections and rounding

Overlapping or repeated proj patterns select each term once. projByAccountTitle from ExchangeAlgebra.Accounting.Exchange, also re-exported by ExchangeAlgebra, selects an account regardless of the other elements of the base.

bar and projNetNorm net within each full base; yen and dollar cash cannot cancel each other. For exact decimal amounts, projNetNorm patterns x agrees with norm (bar (proj patterns x)). Floating-point results can differ because the latter expression rounds each base’s residual before summing.

Caution: compress discards separate term amounts, and floating-point rounding of the direction totals can change the result of a later bar. Preserve the original algebra when individual terms are needed.

Exchange algebra

Class or operationInputs and result
ExBaseClassA HatBaseClass base with account access. Implement getAccountTitle and setAccountTitle; the setter must retain the other elements and direction.
whatDiv, isContra, whatPIMO, fixedCurrentClassify an account from its base. The defaults use the account registry.
whichSideReturn the debit or credit side from account classification and Hat or Not. A query direction HatNot causes an error.
decL, decRSelect debit (left) or credit (right) terms without changing their amounts or aggregating them.
decP, decMdecP selects Hat terms; decM selects Not terms. These directions are distinct from debit and credit.
balanceCompare exact debit and credit sums before rounding, without a tolerance. Return False for non-finite terms.
diffRLReturn the side with the greater exact sum and the difference rounded once; return (Side, 0) for exact equality.

Exchange Alg v b is provided for a HatVal amount type and an ExBaseClass base. Exchange (Journal n) v b is provided when the note type also satisfies Note.

Transfers

A transfer moves an amount from one account to another by adding a journal entry. Keep the January 10 withdrawal and suppose that the business pays 1,200 yen in cash on January 30 for January and February rent, 600 yen for each month. If the payment was initially recorded entirely as rent expense, defer February’s 600 yen to prepaid expenses at January 31.

Use exchangealgebra-0.6.1.1 in the project prepared in Add the package to a Stack project. The example extends Record the withdrawal with the rent payment and its transfer entry. It uses the accounting transfer API from ExchangeAlgebra.Accounting.Transfer, re-exported by ExchangeAlgebra.

Record the rent payment

Save the code blocks in their displayed order as Main.hs. Retain the account-and-unit base and its instance:

Common setup

{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}

module Main where

import ExchangeAlgebra hiding (Yen, Dollar)

-- | Currency elements for the withdrawal and exchange records.
data Unit
    = Yen       -- ^ Japanese yen.
    | Dollar    -- ^ US dollars.
    | Unit      -- ^ Inapplicable in an entry; unrestricted in a query.
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Element Unit where
    wildcard = Unit

-- | Account access for the custom account-and-currency base.
instance ExBaseClass (HatBase (AccountTitles, Unit)) where
    getAccountTitle (_ :< (account, _)) = account
    setAccountTitle (direction :< (_, unit)) account = direction :< (account, unit)

Add the payment to the withdrawal:

Withdrawal definition

-- | January 10: withdraw 3,000 yen from Bank A's savings account into cash.
withdrawal :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
withdrawal = 3000 .@ Not :< (Cash, Yen)
          .+ 3000 .@ Hat :< (Deposits, Yen)
-- | January 30: pay 1,200 yen for January and February rent, initially expensed.
rentPayment :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
rentPayment = 1200 .@ Not :< (RentExpense, Yen)
           .+ 1200 .@ Hat :< (Cash, Yen)

-- | Recorded changes before deferring the February share of rent.
beforeTransfer :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
beforeTransfer = withdrawal .+ rentPayment

The payment debits RentExpense and credits Cash by 1,200 yen. The withdrawal supplies the cash for the payment. beforeTransfer records changes without opening balances; the deposit decrease requires an opening deposit to determine the amount still held.

Specify the source, amount rule, and destination

Definition 9 describes a transfer by a triple: the source base, the destination base, and a value transformation. For the rent adjustment, the source is RentExpense, the transformation takes one half of its balance, and the destination is PrepaidExpenses.

Construct the table with mkTransferTable:

-- | Move half the rent balance to prepaid expenses, retaining its currency.
rentTable :: Either (TransferTableError (HatBase (AccountTitles, Unit)))
                    (TransferTable (HatBase (AccountTitles, Unit)))
rentTable = mkTransferTable
    [ (RentExpense, (.#)) .-> (PrepaidExpenses, (.#)) |% Portion 1 2 ]

Write from .-> to |% share to specify the source, destination, and share. In 0.6.1.1 the accounting API uses whole balances (Relabel) or rational shares (Portion), rather than an arbitrary function. Portion 1 2 moves half of the exact source balance, rounded once with the default Nearest rule. The integer amounts in this example require no rounding.

The amount to transfer is computed from the net balance at each selected full base. At the destination, the debit or credit side of that balance is retained; the direction depends on the destination account’s home side. The returned entry contains a source cancellation and a destination term. Add both terms to the original record to retain its history.

The source wildcard in (RentExpense, (.#)) selects every currency element. The destination wildcard in (PrepaidExpenses, (.#)) retains the selected currency. Here the selected amount is in yen, so the destination is (PrepaidExpenses, Yen). A destination wildcard retains yen as the currency element.

Add the transfer entry and read the balances

Apply the table, handle a rejected table or transfer, and add the returned entry to the original record:

-- | Print a result with the question or operation that produced it.
printNamed :: Show a => String -> a -> IO ()
printNamed label value = putStrLn (label ++ ": " ++ show value)

-- | Generate and retain the adjusting entry, then inspect the net balances.
main :: IO ()
main = case rentTable of
    Left failure -> ioError (userError (show failure))
    Right table -> case transferEntries table beforeTransfer of
        Left failure -> ioError (userError (show failure))
        Right additions -> do
            printNamed "Rent payment" rentPayment
            printNamed "Additional transfer entry" additions
            printNamed "Transfer entry is balanced" (balance additions)
            printNamed "Record retaining original and added terms" (beforeTransfer .+ additions)
            printNamed "Balances after transfer" (bar (beforeTransfer .+ additions))
            printNamed "Record is balanced" (balance (beforeTransfer .+ additions))

Run stack exec -- ghc -Wall -Werror Main.hs -o transfer-example, then run ./transfer-example in your project directory. The program prints:

Rent payment: 1200:@Hat:<(Cash,Yen) .+ 1200:@Not:<(RentExpense,Yen)
Additional transfer entry: 600:@Hat:<(RentExpense,Yen) .+ 600:@Not:<(PrepaidExpenses,Yen)
Transfer entry is balanced: True
Record retaining original and added terms: 1200:@Hat:<(Cash,Yen) .+ 3000:@Not:<(Cash,Yen) .+ 3000:@Hat:<(Deposits,Yen) .+ 600:@Hat:<(RentExpense,Yen) .+ 1200:@Not:<(RentExpense,Yen) .+ 600:@Not:<(PrepaidExpenses,Yen)
Balances after transfer: 1800:@Not:<(Cash,Yen) .+ 3000:@Hat:<(Deposits,Yen) .+ 600:@Not:<(RentExpense,Yen) .+ 600:@Not:<(PrepaidExpenses,Yen)
Record is balanced: True

Additional transfer entry credits RentExpense by 600 yen and debits PrepaidExpenses by 600 yen. Both accounts have debit home sides, so the source cancellation uses Hat and the destination uses Not. The transfer entry is balanced independently of the original record.

The record made with beforeTransfer .+ additions retains the original 1,200-yen expense and the added 600-yen decrease. No implicit bar is applied to that record. For Balances after transfer, apply bar to the combined record: rent expense is 600 yen, prepaid expenses are 600 yen, cash has increased by 1,800 yen, and deposits have decreased by 3,000 yen. The transfer changes the classification of the payment while preserving cash, deposits, currency, and debit-credit equality.

Applying the same Portion 1 2 table again would move half the remaining rent balance. Add this adjusting entry once for the stated January 31 adjustment.

Tested with exchangealgebra-0.6.1.1 on 2026-11-20.

Reference

OperationInputs and result
from .-> to |% RelabelMove the whole exact balance from source to destination. The bases omit Hat/Not; the destination’s direction is derived to retain the source balance’s debit or credit side.
from .-> to |% Portion n dMove n/d of the balance, with 0 < n <= d.
mkTransferTable rowsValidate rows and return Either. Reject invalid portions, overlapping sources, and backward flow, including a cycle or a row to itself. Keep the written row order.
transferEntries table recordReturn Either containing only the additional cancellation and destination terms. Read exact balances; retain the original record by adding the result with .+.
transferEntriesWith rounding table recordChoose the rounding rule for portions. The default of transferEntries is Nearest.

The preprint orders rules by source base; the accounting table instead uses the supplied row order. Each row reads the balances left by earlier rows. A whole-balance transfer table closes its selected sources and is idempotent after its entries have been added. A portion table generally is not idempotent.

A transfer can fail on selected invalid terms, unclassified accounts, or an amount that cannot be represented under the rounding rule. Handle Left before adding any entries; no partial successful record is returned. Use positive, finite amounts through .@, as in Construction and scalar checks.

The generic ExchangeAlgebra.Algebra.Transfer API works on individual terms and is separate from this accounting API. Unit conversion changes the measure of an amount and is not the accounting reclassification used for the rent adjustment.

Journals

The January 10 withdrawal has a date and a description, “Withdrawal from Bank A.” Keep those facts in a journal note so they remain available for selecting transactions without including them as elements in the base used for account balances. A Journal n v b associates each note of type n with an Alg v b.

Use exchangealgebra-0.6.1.1 in the project prepared in Add the package to a Stack project. The example attaches notes to the month’s transactions from Add the month’s transactions, adds a February purchase, then selects entries by note, base, and date range. The note set, finite journal, and operations correspond to Definitions 10–12.

Declare a note type

Save the code blocks in their displayed order as Main.hs. Use the qualified journal import for constructors and queries, and import (.|) separately to attach notes.

Common imports and language extensions

{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}

module Main where

import ExchangeAlgebra hiding (Yen, Dollar)
import ExchangeAlgebra.Journal ((.|))
import qualified ExchangeAlgebra.Journal as Journal

Common declarations

-- | Currency elements for the withdrawal and exchange records.
data Unit
    = Yen       -- ^ Japanese yen.
    | Dollar    -- ^ US dollars.
    | Unit      -- ^ Inapplicable in an entry; unrestricted in a query.
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Element Unit where
    wildcard = Unit

-- | Account access for the custom account-and-currency base.
instance ExBaseClass (HatBase (AccountTitles, Unit)) where
    getAccountTitle (_ :< (account, _)) = account
    setAccountTitle (direction :< (_, unit)) account = direction :< (account, unit)

Declare a note containing the date and description:

-- | A year, month, and day, compared in calendar order for the valid dates used here.
-- This alias does not validate dates or distinguish them from other integer tuples.
type EntryDate = (Integer, Int, Int)

-- | Date and description shared by all terms in one journal entry.
data EntryNote = EntryNote
    { entryDate        :: EntryDate -- ^ Calendar date of the transaction.
    , entryDescription :: String    -- ^ Human-readable description.
    } deriving (Eq, Ord, Show, Generic, Hashable)

instance Journal.Note EntryNote where
    plank = EntryNote (0, 0, 0) ""

-- | Metadata for the withdrawal; the blank note is reserved for aggregation.
withdrawalNote :: EntryNote
withdrawalNote = EntryNote (2026, 1, 10) "Withdrawal from Bank A"

EntryDate is a tuple ordered by year, month, and day. The example supplies valid dates directly; the alias performs no calendar validation. EntryNote derives equality, total ordering, display, and hashing. Typeable, another superclass of Note, is supplied automatically by GHC. Define the distinguished empty note with plank; the remaining methods have defaults.

The value EntryNote (0, 0, 0) "" is reserved for the empty note and is not a transaction date. plank is also the all-notes wildcard for projWithNote. A note identifies a group of terms, not necessarily a unique transaction: two entries with exactly the same date and description share a key and their terms are added. Include a transaction identifier in a note if those entries must remain separately selectable.

Attach notes to the month

Construct each transaction as an algebra, then attach its note once with .|:

Withdrawal definition

-- | January 10: withdraw 3,000 yen from Bank A's savings account into cash.
withdrawal :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
withdrawal = 3000 .@ Not :< (Cash, Yen)
          .+ 3000 .@ Hat :< (Deposits, Yen)
-- | January 15: withdraw another 2,000 yen.
secondWithdrawal :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
secondWithdrawal = 2000 .@ Not :< (Cash, Yen)
                .+ 2000 .@ Hat :< (Deposits, Yen)

-- | January 20: buy goods for 500 yen in cash.
cashPayment :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
cashPayment = 500 .@ Hat :< (Cash, Yen)
           .+ 500 .@ Not :< (Purchases, Yen)

-- | January 25: exchange 1,500 yen for 10 dollars without a fee.
currencyExchange :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
currencyExchange = 1500 .@ Hat :< (Cash, Yen)
                .+   10 .@ Not :< (Cash, Dollar)

-- | February 1: buy goods for 400 yen in cash.
februaryPurchase :: Alg MoneyDecimal (HatBase (AccountTitles, Unit))
februaryPurchase = 400 .@ Not :< (Purchases, Yen)
                .+ 400 .@ Hat :< (Cash, Yen)

-- | Metadata for the February purchase, excluded by the January date range.
februaryNote :: EntryNote
februaryNote = EntryNote (2026, 2, 1) "Purchase of goods"

-- | January transactions and one February purchase, each with a date and description.
transactions :: Journal.Journal EntryNote MoneyDecimal (HatBase (AccountTitles, Unit))
transactions = (withdrawal .| withdrawalNote)
            .+ (secondWithdrawal .| EntryNote (2026, 1, 15) "Withdrawal from Bank A")
            .+ (cashPayment .| EntryNote (2026, 1, 20) "Purchase of goods")
            .+ (currencyExchange .| EntryNote (2026, 1, 25) "Yen-dollar exchange")
            .+ (februaryPurchase .| februaryNote)

The two terms of the January 10 withdrawal share withdrawalNote. The January 15 withdrawal has a different date, so it remains separately selectable even though its description is the same. Adding journals with .+ keeps the notes and concatenates the term sequences at a shared note; it does not net the terms.

The January 20 purchase debits Purchases and credits Cash. The January 25 exchange reduces yen cash by 1,500 yen and increases dollar cash by 10 dollars at 150 yen per dollar, without a fee. Keep currencies separate when totaling amounts; the raw yen and dollar numbers are not a common-unit debit-credit comparison.

On February 1, the business buys another 400 yen of goods for cash. Record a debit to Purchases and a credit to Cash, both for 400 yen. transactions contains the four January entries and this February entry.

Select by note, base, and date

For a date range, test the date field with filterWithNote. Use an inclusive lower bound and an exclusive upper bound:

-- | Select entries with an inclusive lower and exclusive upper date.
isInJanuary :: EntryNote -> Alg MoneyDecimal (HatBase (AccountTitles, Unit)) -> Bool
isInJanuary note _ = (2026, 1, 1) <= entryDate note && entryDate note < (2026, 2, 1)

-- | Keep the notes while selecting the dates in January.
january :: Journal.Journal EntryNote MoneyDecimal (HatBase (AccountTitles, Unit))
january = Journal.filterWithNote isInJanuary transactions

january contains the four January entries and excludes the February 1 purchase. The predicate selects by date even when the descriptions differ. projWithNote [withdrawalNote] instead selects an exact note, including both its date and description. projWithBase selects terms while retaining their notes, and projWithNoteBase combines both restrictions.

Total amounts and combine notes

Print the February entry before and after date selection, the selected January records, the gross cash amount, and the cash balances:

-- | Print a result with the question or operation that produced it.
printNamed :: Show a => String -> a -> IO ()
printNamed label value = putStrLn (label ++ ": " ++ show value)

-- | Ask questions by note, base, and date, then combine notes for net balances.
main :: IO ()
main = do
    printNamed "February 1 entry before date selection"
        (Journal.projWithNote [februaryNote] transactions)
    printNamed "February 1 entry after January selection"
        (Journal.projWithNote [februaryNote] january)
    printNamed "January 10 entry" (Journal.projWithNote [withdrawalNote] transactions)
    printNamed "January 10 cash terms"
        (Journal.projWithNoteBase [withdrawalNote] [HatNot :< (Cash, Yen)] transactions)
    printNamed "January yen cash terms"
        (Journal.projWithBase [HatNot :< (Cash, Yen)] january)
    printNamed "January gross yen cash amount"
        (norm (Journal.projWithBase [HatNot :< (Cash, Yen)] january))
    printNamed "January cash balances by currency"
        (proj [HatNot :< (Cash, (.#))] (bar (Journal.toAlg january)))
    printNamed "Gathered January record" (Journal.gather Journal.plank january)
    printNamed "Bar across notes at plank" (bar january)

Run stack exec -- ghc -Wall -Werror Main.hs -o journal-example, then run ./journal-example in your project directory. The program prints:

February 1 entry before date selection: 400:@Not:<(Purchases,Yen) .+ 400:@Hat:<(Cash,Yen) .| EntryNote {entryDate = (2026,2,1), entryDescription = "Purchase of goods"}
February 1 entry after January selection: 0
January 10 entry: 3000:@Hat:<(Deposits,Yen) .+ 3000:@Not:<(Cash,Yen) .| EntryNote {entryDate = (2026,1,10), entryDescription = "Withdrawal from Bank A"}
January 10 cash terms: 3000:@Not:<(Cash,Yen) .| EntryNote {entryDate = (2026,1,10), entryDescription = "Withdrawal from Bank A"}
January yen cash terms: (500:@Hat:<(Cash,Yen) .| EntryNote {entryDate = (2026,1,20), entryDescription = "Purchase of goods"}) .+ (3000:@Not:<(Cash,Yen) .| EntryNote {entryDate = (2026,1,10), entryDescription = "Withdrawal from Bank A"}) .+ (2000:@Not:<(Cash,Yen) .| EntryNote {entryDate = (2026,1,15), entryDescription = "Withdrawal from Bank A"}) .+ (1500:@Hat:<(Cash,Yen) .| EntryNote {entryDate = (2026,1,25), entryDescription = "Yen-dollar exchange"})
January gross yen cash amount: 7000
January cash balances by currency: 3000:@Not:<(Cash,Yen) .+ 10:@Not:<(Cash,Dollar)
Gathered January record: 500:@Hat:<(Cash,Yen) .+ 1500:@Hat:<(Cash,Yen) .+ 2000:@Not:<(Cash,Yen) .+ 3000:@Not:<(Cash,Yen) .+ 10:@Not:<(Cash,Dollar) .+ 2000:@Hat:<(Deposits,Yen) .+ 3000:@Hat:<(Deposits,Yen) .+ 500:@Not:<(Purchases,Yen)
Bar across notes at plank: 3000:@Not:<(Cash,Yen) .+ 10:@Not:<(Cash,Dollar) .+ 5000:@Hat:<(Deposits,Yen) .+ 500:@Not:<(Purchases,Yen)

February 1 entry before date selection contains the 400-yen purchase with its February date. February 1 entry after January selection is 0, so the purchase is absent from the January selection.

January gross yen cash amount is 7,000 yen: increases of 3,000 and 2,000 plus decreases of 500 and 1,500. norm counts all selected amounts in both directions. For January cash balances by currency, toAlg removes the note keys without netting, and bar then cancels within each account-and-currency base. The resulting cash changes are 3,000 yen and 10 dollars.

Journal.gather Journal.plank january combines all entries under the empty note without canceling opposing terms. bar january combines the notes under plank and nets the combined algebra. It loses the original dates and descriptions. A component under plank is printed without a note suffix, but the value remains a Journal. To net separately within each note, use Journal.map bar january; retain january itself when the original term detail is required.

Tested with exchangealgebra-0.6.1.1 on 2026-11-20.

Reference

Type or operationInputs and result
Note nRequires Show, Eq, Ord, Hashable, and Typeable. Define plank; isPlank defaults to equality with plank.
algebra .| noteAttach one note to all terms of an algebra. A zero algebra produces an empty journal.
Journal.fromList entriesSum a list of journals, combining equal note keys with redundant addition.
Journal.sigma items fSum the journals produced by applying f to the items.
Journal.projWithNote notes journalSelect exact note keys. A list containing plank selects all notes; an empty list selects none.
Journal.projWithBase bases journalSelect matching terms at every note. Drop a note whose selected algebra is zero.
Journal.projWithNoteBase notes bases journalRestrict notes and bases. An empty note list or a list containing plank imposes no note restriction. An empty base list selects nothing.
Journal.filterWithNote predicate journalKeep note-algebra pairs satisfying the predicate.
Journal.toAlg journalRemove note keys and add their algebras, retaining term amounts without netting.
Journal.gather note journalPut the combined algebra under the specified note, without netting.
bar journalGather under plank, then net the combined algebra.
Journal.map f journalApply an algebra transformation separately at each note.

Hat and scalar multiplication preserve note keys. compress aggregates within each note, while norm totals all amounts across notes. An account projection of the raw journal retains opposing amounts in different notes. Combine the notes before reading a balance that must cancel an original entry against an adjustment recorded under a different note.

Multiple accounting entities

The January 10 withdrawal appears in two accounting records. The business receives 3,000 yen in cash and reduces its deposit asset. Bank A reduces the deposit liability it owes to the business and pays out 3,000 yen in cash. Add an element that identifies the accounting entity to the base to keep both records in one algebra while retaining whose accounts each term describes.

Use exchangealgebra-0.6.1.1 in the project prepared in Add the package to a Stack project. The example extends Record the withdrawal from HatBase (AccountTitles, Unit) to HatBase (AccountTitles, Owner, Unit). The same algebra operations apply to bases that also identify the accounting entity.

Add an element type for accounting entities

Save the code blocks in their displayed order as Main.hs. Retain the currency declaration:

Common setup

{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}

module Main where

import ExchangeAlgebra hiding (Yen, Dollar)

-- | Currency elements for the withdrawal and exchange records.
data Unit
    = Yen       -- ^ Japanese yen.
    | Dollar    -- ^ US dollars.
    | Unit      -- ^ Inapplicable in an entry; unrestricted in a query.
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Element Unit where
    wildcard = Unit

Declare the accounting entities and account access for the expanded base:

-- | Owners of the two accounting records.
data Owner
    = Business  -- ^ The business withdrawing its own deposit.
    | BankA     -- ^ The bank paying out the withdrawal.
    | Owner     -- ^ Inapplicable in an entry; unrestricted in a query.
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Element Owner where
    wildcard = Owner

-- | Account access for bases with an owner and a currency.
instance ExBaseClass (HatBase (AccountTitles, Owner, Unit)) where
    getAccountTitle (_ :< (account, _, _)) = account
    setAccountTitle (direction :< (_, owner, unit)) account = direction :< (account, owner, unit)

Business and BankA identify the accounting entities. Owner is the wildcard element, used in queries to select both entities. getAccountTitle reads the account element, and setAccountTitle changes only that element. This custom base shape needs its own ExBaseClass instance; the Alg exchange operations are unchanged.

Record both sides of the withdrawal

Construct each entity’s balanced record, then add the records:

-- | The business receives cash and reduces its deposit asset.
businessRecord :: Alg MoneyDecimal (HatBase (AccountTitles, Owner, Unit))
businessRecord = 3000 .@ Not :< (Cash, Business, Yen)
              .+ 3000 .@ Hat :< (Deposits, Business, Yen)

-- | Bank A reduces its deposit liability and pays out cash.
bankRecord :: Alg MoneyDecimal (HatBase (AccountTitles, Owner, Unit))
bankRecord = 3000 .@ Hat :< (DepositPayable, BankA, Yen)
          .+ 3000 .@ Hat :< (Cash, BankA, Yen)

-- | Retain both owners' records in one algebra without canceling between owners.
combined :: Alg MoneyDecimal (HatBase (AccountTitles, Owner, Unit))
combined = businessRecord .+ bankRecord

The business debits Cash and credits Deposits. Bank A debits DepositPayable, an ordinary liability account for deposits accepted, and credits Cash. The bank’s liability decrease has direction Hat but is a debit because an ordinary liability’s home side is credit. Both bank terms therefore use Hat, yet they fall on opposite debit and credit sides.

DepositPayable describes a bank deposit liability. DepositsReceived describes other deposits held, so the bank record uses DepositPayable. Neither entity records revenue or expense for this withdrawal. Every amount remains nonnegative.

Select entities and corresponding terms

Restrict the accounting entity element to read one entity’s record. Select the deposit asset and liability with separate patterns:

-- | Select one owner's complete accounting record.
recordOf :: Owner -> Alg MoneyDecimal (HatBase (AccountTitles, Owner, Unit))
recordOf owner = proj [HatNot :< ((.#), owner, (.#))] combined

-- | Select the business deposit asset and the bank's corresponding liability.
depositPair :: Alg MoneyDecimal (HatBase (AccountTitles, Owner, Unit))
depositPair = proj [ HatNot :< (Deposits, Business, Yen)
                   , HatNot :< (DepositPayable, BankA, Yen) ] combined

recordOf Business contains both business terms, and recordOf BankA contains both bank terms. The cash increase of the business corresponds to the bank’s cash decrease. The business’s deposit asset decrease corresponds to the bank’s deposit liability decrease. These correspondences concern the same transaction, but the full bases differ in entity or account, so the terms do not cancel automatically.

Check each entity’s record

Print the entity selections, balance checks, and corresponding movements:

-- | Print a result with the question or operation that produced it.
printNamed :: Show a => String -> a -> IO ()
printNamed label value = putStrLn (label ++ ": " ++ show value)

-- | Inspect each owner and the corresponding cash and deposit movements.
main :: IO ()
main = do
    printNamed "Business record" (recordOf Business)
    printNamed "Bank A record" (recordOf BankA)
    printNamed "Business record is balanced" (balance (recordOf Business))
    printNamed "Bank A record is balanced" (balance (recordOf BankA))
    printNamed "Combined record is balanced" (balance combined)
    printNamed "Bank liability decrease side" (whichSide (Hat :< (DepositPayable, BankA, Yen)))
    printNamed "Corresponding deposit changes" depositPair
    printNamed "Cash changes with owners retained" (proj [HatNot :< (Cash, (.#), Yen)] combined)
    printNamed "Bar retains separate owners" (bar combined)

Run stack exec -- ghc -Wall -Werror Main.hs -o agents-example, then run ./agents-example in your project directory. The program prints:

Business record: 3000:@Not:<(Cash,Business,Yen) .+ 3000:@Hat:<(Deposits,Business,Yen)
Bank A record: 3000:@Hat:<(Cash,BankA,Yen) .+ 3000:@Hat:<(DepositPayable,BankA,Yen)
Business record is balanced: True
Bank A record is balanced: True
Combined record is balanced: True
Bank liability decrease side: Debit
Corresponding deposit changes: 3000:@Hat:<(Deposits,Business,Yen) .+ 3000:@Hat:<(DepositPayable,BankA,Yen)
Cash changes with owners retained: 3000:@Not:<(Cash,Business,Yen) .+ 3000:@Hat:<(Cash,BankA,Yen)
Bar retains separate owners: 3000:@Not:<(Cash,Business,Yen) .+ 3000:@Hat:<(Cash,BankA,Yen) .+ 3000:@Hat:<(Deposits,Business,Yen) .+ 3000:@Hat:<(DepositPayable,BankA,Yen)

The business, bank, and combined records are balanced in yen. Check each entity individually: a combined balance alone could conceal an imbalance in one entity offset by another. Bar retains separate owners still contains both entities’ cash terms because bar cancels only within a full base, including the accounting entity element.

The accounting entity element identifies the entity whose record contains the term. Counterparty identity is separate. With only one business and one bank the correspondence is specified by the example. To identify particular pairs in a larger set of transactions, add the counterparty or a shared transaction identifier to the note type, as described in Declare a note type.

Tested with exchangealgebra-0.6.1.1 on 2026-11-20.

Reference

Construction or operationInputs and result
HatBase (AccountTitles, Owner, Unit)Identify the account, the accounting entity, and the currency. Direction is separate from the tuple.
Element OwnerSupply a wildcard element and derive consistent equality, ordering, and hashing.
ExBaseClass instanceRead and replace the account while preserving entity, currency, and direction.
proj [HatNot :< ((.#), owner, (.#))]Select one entity across accounts, directions, and currencies.
proj [HatNot :< (Cash, (.#), Yen)]Select yen cash movements across entities, retaining the accounting entity elements.
balance (recordOf owner)Compare debit and credit sums for the selected entity. The example uses only yen.
bar combinedNet within each full base. Keep different entities separate.

The accounting entity element set is an ordinary element set for a base under Definitions 1–3. The additional element of the base changes neither redundant addition nor the debit and credit decomposition. It changes which terms share a full base and which entities can be selected in a query.

Account titles and their attributes

AccountTitles is the element type for account titles. Each constructor, such as Cash, is an element. The wildcard element AccountTitle has no account attributes. Both accountSpec AccountTitle and accountSemantics AccountTitle return Nothing.

Account specification

Use accountSpec to get the AccountSpec record for a concrete account title.

  • asDivision gives the division. The values are Assets for assets, Liability for liabilities, Equity for equity, Revenue for revenue, and Cost for expenses.
  • asClosing gives the automatic closing rule. CloseByDivision uses the division to determine eligibility and transfer direction. NoClose skips automatic closing for the account.
  • asIsContra identifies contra accounts, which offset balances in their division.
  • asFixedCurrent classifies the account as Fixed, Current, or Other. For example, revenue and expense accounts use Other.
  • asNameEn gives the English name. asNameJa gives the Japanese name, which may include notes. asLabelJa gives the Japanese display name without notes.
  • asDescription gives a description of the account.
  • asAliases lists the aliases in the registry. accountAliases combines these with aliases from the Japan Chamber of Commerce and Industry’s account names.

Account semantics

Use accountSemantics to get the AccountSemantics record for bookkeeping and reporting.

  • asemRoles lists the roles of the account. An account can have multiple roles. OrdinaryAccount marks an ordinary account, ContraAccount offsets another balance, and ReciprocalAccount matches balances between entities. SuspenseOrClearingAccount holds amounts temporarily. ClosingDevice supports closing entries. AttributionAccount assigns amounts to a group. PeriodResult represents a period result and ReportingSubtotal represents a subtotal.
  • asemPostingCapability describes where the account may be used. OrdinaryPosting allows ordinary entries. ClosingOnly, ConsolidationOnly, and EngineGeneratedOnly limit use to closing, consolidation, and entries generated by the library, respectively. NotPostable marks an account unavailable for recording entries.
  • asemDivisionSemantics explains what the division represents. StatementDivision gives a financial statement classification. BookkeepingControlClass gives a class used to control a bookkeeping procedure. DirectionEncoding uses the division to encode direction. NoStatementDivision indicates that no statement division applies.
  • asemHomeSideSemantics describes the home side, the debit or credit side on which you record an increase in the account. FixedHomeSide specifies Debit or Credit. ContextDependentHomeSide depends on the context. NoFixedHomeSide gives no single home side. NoPostingSide means that no posting side applies.
  • asemReportingEligibility describes eligibility for financial statement presentation. StatementEligible marks an eligible account. ContextualPresentation depends on the reporting context. DerivedPresentation represents a derived result or subtotal. NotPresented excludes the account from presentation.

Where the attributes are used

  • Closing entries use the closing rule and division to select accounts to close. The division and contra status determine the transfer direction.
  • Financial statements use the statement division and the fixed/current classification to group lines. The ContraAccount role determines whether a balance is presented as a deduction.
  • Reading journals from CSV uses accountAliases to resolve alternate names.
  • Trial balance and checks use the home side to flag ordinary accounts with a balance on the opposite side. They use roles to check balances in accounts such as suspense and clearing accounts.

Compare cash and accumulated depreciation

This program prints the classification and semantics for Cash and AccumulatedDepreciation, followed by the aliases for Cash.

module Main where

import ExchangeAlgebra
    ( AccountSemantics(..)
    , AccountSpec(..)
    , AccountTitles(..)
    , accountAliases
    , accountSemantics
    , accountSpec
    )
import System.Exit (die)

main :: IO ()
main = do
    describe Cash
    describe AccumulatedDepreciation
    mapM_ putStrLn (map (read . show) (accountAliases Cash) :: [String])

describe :: AccountTitles -> IO ()
describe title = case (accountSpec title, accountSemantics title) of
    (Just spec, Just semantics) ->
        mapM_ putStrLn
            [ show title
            , show (asDivision spec, asClosing spec, asIsContra spec, asFixedCurrent spec)
            , show (asemRoles semantics, asemPostingCapability semantics)
            , show (asemDivisionSemantics semantics, asemHomeSideSemantics semantics)
            , show (asemReportingEligibility semantics)
            ]
    _ -> die "Missing account attributes"
Cash
(Assets,CloseByDivision,False,Current)
([OrdinaryAccount],OrdinaryPosting)
(StatementDivision Assets,FixedHomeSide Debit)
StatementEligible
AccumulatedDepreciation
(Assets,CloseByDivision,True,Fixed)
([OrdinaryAccount,ContraAccount],OrdinaryPosting)
(StatementDivision Assets,FixedHomeSide Credit)
StatementEligible
現金

Tested with exchangealgebra-0.6.1.1 on 2026-11-20.

English names shared by multiple accounts

Use constructor names or Japanese names to distinguish accounts that share an English name. The built-in list gives both. In exchangealgebra-0.6.1.1, the following pairs share an asNameEn value.

  • Retained earnings (RetainedEarnings and EarnedSurplus)
  • Supplies (SuppliesExpenses and SuppliesOnHand)
  • Central bank payment to treasury (CentralBankPaymentExpense and CentralBankPaymentIncome)
  • Provision for repairs (AllowanceForRepairs and ProvisionForRepairs)
  • Provision for warranties (AllowanceForProductWarranties and ProvisionForProductWarranties)
  • Provision for bonuses (AllowanceForBonuses and ProvisionForBonuses)

The English name of Building is “Real estate”.

Built-in account titles

The tables group concrete account titles by asDivision. Within each table, rows follow the order of concreteAccountTitles.

  • Constructor is the Haskell constructor name.
  • English name and Japanese name give the English name and the Japanese display name without notes.
  • Fixed/current gives the fixed or current classification. Other covers accounts outside these classes.
  • Home side gives the side on which you record an increase, or indicates that a fixed side does not apply.
  • Closing rule gives the rule for automatic closing.
  • Roles lists roles other than OrdinaryAccount, including ContraAccount for contra accounts. An account with only the ordinary role has a blank cell.

See Account titles and their attributes for the meaning of each value.

Assets

ConstructorEnglish nameJapanese nameFixed/currentHome sideClosing ruleRoles
CashCash現金CurrentFixedHomeSide DebitCloseByDivision
DepositsSavings deposits普通預金CurrentFixedHomeSide DebitCloseByDivision
CurrentDepositsCurrent deposits当座預金CurrentFixedHomeSide DebitCloseByDivision
SecuritiesSecurities有価証券CurrentFixedHomeSide DebitCloseByDivision
InvestmentSecuritiesInvestment securities投資有価証券FixedFixedHomeSide DebitCloseByDivision
InvestmentInAssociateInvestment in associate関係会社株式FixedFixedHomeSide DebitCloseByDivision
LongTermNationalBondsLong-term national bonds長期国債FixedFixedHomeSide DebitCloseByDivision
ShortTermNationalBondsShort-term national bonds短期国債CurrentFixedHomeSide DebitCloseByDivision
ProductsProducts商品CurrentFixedHomeSide DebitCloseByDivision
MachineryMachinery and equipment機械装置FixedFixedHomeSide DebitCloseByDivision
BuildingReal estate建物FixedFixedHomeSide DebitCloseByDivision
VehicleVehicles車両運搬具FixedFixedHomeSide DebitCloseByDivision
StockInvestmentStock investment株式投資OtherFixedHomeSide DebitCloseByDivision
EquipmentInvestmentEquipment investment設備投資FixedFixedHomeSide DebitCloseByDivision
LongTermLoansReceivableLong-term loans receivable長期貸付金FixedFixedHomeSide DebitCloseByDivision
AccountsReceivableAccounts receivable売掛金CurrentFixedHomeSide DebitCloseByDivision
ShortTermLoansReceivableShort-term loans receivable短期貸付金CurrentFixedHomeSide DebitCloseByDivision
ReserveDepositReceivableReserve deposits, asset side準備預金CurrentFixedHomeSide DebitCloseByDivision
GoldGold金FixedFixedHomeSide DebitCloseByDivision
GovernmentServiceGovernment service政府サービスCurrentFixedHomeSide DebitCloseByDivision
PettyCashPetty cash小口現金CurrentFixedHomeSide DebitCloseByDivision
NotesReceivableNotes receivable受取手形CurrentFixedHomeSide DebitCloseByDivision
ElectronicallyRecordedReceivableElectronically recorded monetary claims電子記録債権CurrentFixedHomeSide DebitCloseByDivision
CreditCardReceivableCredit card receivableクレジット売掛金CurrentFixedHomeSide DebitCloseByDivision
NotesLoansReceivableLoans receivable on notes手形貸付金CurrentFixedHomeSide DebitCloseByDivision
MerchandiseInventoryMerchandise inventory繰越商品CurrentFixedHomeSide DebitCloseByDivision
AdvancesPaidAdvances paid前払金CurrentFixedHomeSide DebitCloseByDivision
PrepaidExpensesPrepaid expenses前払費用CurrentFixedHomeSide DebitCloseByDivision
AccruedRevenueAccrued revenue未収収益CurrentFixedHomeSide DebitCloseByDivision
OtherReceivablesOther receivables未収入金CurrentFixedHomeSide DebitCloseByDivision
PaymentsOnBehalfPayments made on behalf立替金CurrentFixedHomeSide DebitCloseByDivision
SuspensePaymentsSuspense payments仮払金CurrentFixedHomeSide DebitCloseByDivisionSuspenseOrClearingAccount
ConsumptionTaxPaidConsumption tax paid仮払消費税CurrentFixedHomeSide DebitCloseByDivision
PrepaidCorporateIncomeTaxesPrepaid corporate income taxes仮払法人税等CurrentFixedHomeSide DebitCloseByDivision
LandLand土地FixedFixedHomeSide DebitCloseByDivision
FixturesFixtures and equipment備品FixedFixedHomeSide DebitCloseByDivision
PatentPatent特許権FixedFixedHomeSide DebitCloseByDivision
TrademarkTrademark商標権FixedFixedHomeSide DebitCloseByDivision
SoftwareSoftwareソフトウェアFixedFixedHomeSide DebitCloseByDivision
CashOverShortCash over and short現金過不足OtherContextDependentHomeSideCloseByDivisionSuspenseOrClearingAccount
AllowanceForDoubtfulAccountsAllowance for doubtful accounts貸倒引当金CurrentFixedHomeSide CreditCloseByDivisionContraAccount
AccumulatedDepreciationAccumulated depreciation減価償却累計額FixedFixedHomeSide CreditCloseByDivisionContraAccount
TimeDepositsTime deposits定期預金CurrentFixedHomeSide DebitCloseByDivision
LoansReceivableLoans receivable貸付金CurrentFixedHomeSide DebitCloseByDivision
GiftCertificatesReceivedGift certificates received受取商品券CurrentFixedHomeSide DebitCloseByDivision
SecurityDepositsPaidGuarantee deposits差入保証金FixedFixedHomeSide DebitCloseByDivision
SuppliesOnHandSupplies貯蔵品CurrentFixedHomeSide DebitCloseByDivision
ContractAssetsContract assets契約資産CurrentFixedHomeSide DebitCloseByDivision
IncomeTaxesRefundReceivableIncome taxes refund receivable未収還付法人税等CurrentFixedHomeSide DebitCloseByDivision
WorkInProcessWork in process仕掛品CurrentFixedHomeSide DebitCloseByDivision
DeferredTaxAssetsDeferred tax assets繰延税金資産FixedFixedHomeSide DebitCloseByDivision
LeasedAssetsLeased assetsリース資産FixedFixedHomeSide DebitCloseByDivision
ToolsAndInstrumentsTools and instruments工具器具FixedFixedHomeSide DebitCloseByDivision
ConstructionInProgressConstruction in progress建設仮勘定FixedFixedHomeSide DebitCloseByDivision
GoodwillGoodwillのれんFixedFixedHomeSide DebitCloseByDivision
SoftwareInProgressSoftware in progressソフトウェア仮勘定FixedFixedHomeSide DebitCloseByDivision
LongTermPrepaidExpensesLong-term prepaid expenses長期前払費用FixedFixedHomeSide DebitCloseByDivision
DishonoredNotesReceivableDishonored notes receivable不渡手形CurrentFixedHomeSide DebitCloseByDivision
PrepaidPensionCostPrepaid pension costs前払年金費用FixedFixedHomeSide DebitCloseByDivision
NetDefinedBenefitAssetRetirement benefit asset退職給付に係る資産FixedFixedHomeSide DebitCloseByDivision
DepositsInSpecialAccountsDeposits in special accounts別段預金CurrentFixedHomeSide DebitCloseByDivision
StructuresStructures構築物FixedFixedHomeSide DebitCloseByDivision
LeaseholdRightsLeasehold interests in land借地権FixedFixedHomeSide DebitCloseByDivision
NonOperatingNotesReceivableNon-operating notes receivable営業外受取手形CurrentFixedHomeSide DebitCloseByDivision
NonOperatingElectronicallyRecordedReceivableElectronically recorded monetary claims - non-operating営業外電子記録債権CurrentFixedHomeSide DebitCloseByDivision
IncomeSummaryIncome summary損益OtherContextDependentHomeSideNoCloseClosingDevice
SuspenseAccountSuspense account未決算CurrentContextDependentHomeSideCloseByDivisionSuspenseOrClearingAccount
ContraAccountForGuaranteeObligationsContra account for guarantee obligations保証債務見返OtherFixedHomeSide DebitCloseByDivision
BranchCurrentAccountBranch current account支店OtherFixedHomeSide DebitCloseByDivisionReciprocalAccount
TradingSecuritiesTrading securities売買目的有価証券CurrentFixedHomeSide DebitCloseByDivision
HeldToMaturityBondsHeld-to-maturity bonds満期保有目的債券FixedFixedHomeSide DebitCloseByDivision
SubsidiaryStocksShares of subsidiaries子会社株式FixedFixedHomeSide DebitCloseByDivision
AffiliateStocksShares of associates関連会社株式FixedFixedHomeSide DebitCloseByDivision
AvailableForSaleSecuritiesAvailable-for-sale securitiesその他有価証券FixedFixedHomeSide DebitCloseByDivision
ConsumptionTaxRefundReceivableConsumption tax refund receivable未収還付消費税CurrentFixedHomeSide DebitCloseByDivision
RawMaterialsRaw materials原材料CurrentFixedHomeSide DebitCloseByDivision
GoodsInTransitGoods in transit未着品CurrentFixedHomeSide DebitCloseByDivision

Liabilities

ConstructorEnglish nameJapanese nameFixed/currentHome sideClosing ruleRoles
LongTermLoansPayableLong-term loans payable長期借入金FixedFixedHomeSide CreditCloseByDivision
ShortTermLoansPayableShort-term loans payable短期借入金CurrentFixedHomeSide CreditCloseByDivision
LoansPayableLoans payable借入金CurrentFixedHomeSide CreditCloseByDivision
ReserveForDepreciationReserve for depreciation減価償却引当金CurrentFixedHomeSide CreditCloseByDivision
DepositPayableDeposits accepted受入預金CurrentFixedHomeSide CreditCloseByDivision
LongTermNationalBondsPayableLong-term national bonds payable長期国債FixedFixedHomeSide CreditCloseByDivision
ShortTermNationalBondsPayableShort-term national bonds payable短期国債CurrentFixedHomeSide CreditCloseByDivision
ReserveDepositPayableReserve deposits, liability side準備預金CurrentFixedHomeSide CreditCloseByDivision
CentralBankNotePayableCentral bank notes発行銀行券CurrentFixedHomeSide CreditCloseByDivision
AccountsPayableAccounts payable買掛金CurrentFixedHomeSide CreditCloseByDivision
NotesPayableNotes payable支払手形CurrentFixedHomeSide CreditCloseByDivision
ElectronicallyRecordedObligationsElectronically recorded monetary obligations電子記録債務CurrentFixedHomeSide CreditCloseByDivision
NotesLoansPayableLoans payable on notes手形借入金CurrentFixedHomeSide CreditCloseByDivision
BankOverdraftBank overdraft当座借越CurrentFixedHomeSide CreditCloseByDivision
AdvancesReceivedAdvances received前受金CurrentFixedHomeSide CreditCloseByDivision
UnearnedRevenueUnearned revenue前受収益CurrentFixedHomeSide CreditCloseByDivision
AccruedExpensesAccrued expenses未払費用CurrentFixedHomeSide CreditCloseByDivision
OtherPayablesOther payables未払金CurrentFixedHomeSide CreditCloseByDivision
DepositsReceivedDeposits received預り金CurrentFixedHomeSide CreditCloseByDivision
SuspenseReceiptsSuspense receipts仮受金CurrentFixedHomeSide CreditCloseByDivisionSuspenseOrClearingAccount
ConsumptionTaxReceivedConsumption tax received仮受消費税CurrentFixedHomeSide CreditCloseByDivision
AccruedConsumptionTaxAccrued (unpaid) consumption tax未払消費税CurrentFixedHomeSide CreditCloseByDivision
AccruedCorporateIncomeTaxesAccrued (unpaid) corporate income taxes未払法人税等CurrentFixedHomeSide CreditCloseByDivision
UnpaidDividendsUnpaid dividends未払配当金CurrentFixedHomeSide CreditCloseByDivision
RefundLiabilitiesRefund liabilities返金負債CurrentFixedHomeSide CreditCloseByDivision
NonOperatingNotesPayableNon-operating notes payable営業外支払手形CurrentFixedHomeSide CreditCloseByDivision
NonOperatingElectronicallyRecordedObligationsElectronically recorded obligations - non-operating営業外電子記録債務CurrentFixedHomeSide CreditCloseByDivision
BonusesPayableAccrued bonuses未払賞与CurrentFixedHomeSide CreditCloseByDivision
AllowanceForRepairsProvision for repairs修繕引当金CurrentFixedHomeSide CreditCloseByDivision
AllowanceForProductWarrantiesProvision for warranties商品保証引当金CurrentFixedHomeSide CreditCloseByDivision
AllowanceForBonusesProvision for bonuses賞与引当金CurrentFixedHomeSide CreditCloseByDivision
DeferredTaxLiabilitiesDeferred tax liabilities繰延税金負債FixedFixedHomeSide CreditCloseByDivision
LeaseObligationsLease liabilitiesリース債務FixedFixedHomeSide CreditCloseByDivision
GuaranteeDepositsReceivedGuarantee deposits received預り保証金FixedFixedHomeSide CreditCloseByDivision
AllowanceForRetirementBenefitsProvision for retirement benefits退職給付引当金FixedFixedHomeSide CreditCloseByDivision
LongTermOtherPayablesLong-term accounts payable - other長期未払金FixedFixedHomeSide CreditCloseByDivision
NetDefinedBenefitLiabilityRetirement benefit liability退職給付に係る負債FixedFixedHomeSide CreditCloseByDivision
GuaranteeObligationsGuarantee obligations保証債務OtherFixedHomeSide CreditCloseByDivision
HeadOfficeCurrentAccountHead office current account本店OtherFixedHomeSide CreditCloseByDivisionReciprocalAccount
PropertyTaxPayableProperty tax payable未払固定資産税CurrentFixedHomeSide CreditCloseByDivision
DepositsReceivedFromOfficersDeposits received from officers役員預り金CurrentFixedHomeSide CreditCloseByDivision

Equity

ConstructorEnglish nameJapanese nameFixed/currentHome sideClosing ruleRoles
CapitalStockCapital stock資本金OtherFixedHomeSide CreditCloseByDivision
RetainedEarningsRetained earnings繰越利益剰余金OtherFixedHomeSide CreditCloseByDivision
LegalRetainedEarningsLegal (appropriated) retained earnings reserve利益準備金OtherFixedHomeSide CreditCloseByDivision
CumulativeTranslationAdjustmentCumulative translation adjustment為替換算調整勘定OtherFixedHomeSide CreditCloseByDivision
StockSubscriptionDepositsDeposits for subscriptions of shares株式申込証拠金OtherFixedHomeSide CreditCloseByDivision
LegalCapitalSurplusLegal capital surplus資本準備金OtherFixedHomeSide CreditCloseByDivision
OtherCapitalSurplusOther capital surplusその他資本剰余金OtherFixedHomeSide CreditCloseByDivision
DividendEqualizationReserveReserve for dividend equalization配当平均積立金OtherFixedHomeSide CreditCloseByDivision
RepairFundReserveReserve for repairs修繕積立金OtherFixedHomeSide CreditCloseByDivision
ConstructionFundReserveReserve for new construction新築積立金OtherFixedHomeSide CreditCloseByDivision
GeneralReserveGeneral reserve別途積立金OtherFixedHomeSide CreditCloseByDivision
ValuationDifferenceOnOtherSecuritiesValuation difference on available-for-sale securitiesその他有価証券評価差額金OtherFixedHomeSide CreditCloseByDivision
NonControllingInterestsNon-controlling interests非支配株主持分OtherFixedHomeSide CreditCloseByDivisionAttributionAccount
CapitalSurplusCapital surplus資本剰余金OtherFixedHomeSide CreditCloseByDivision
EarnedSurplusRetained earnings利益剰余金OtherFixedHomeSide CreditCloseByDivision

Revenue

ConstructorEnglish nameJapanese nameFixed/currentHome sideClosing ruleRoles
ValueAddedValue added付加価値OtherFixedHomeSide CreditCloseByDivision
SubsidyIncomeSubsidy income補助金収入OtherFixedHomeSide CreditCloseByDivision
NationalBondInterestEarnedNational bond interest earned国債利息収入OtherFixedHomeSide CreditCloseByDivision
DepositInterestEarnedDeposit interest earned預金利息収入OtherFixedHomeSide CreditCloseByDivision
GrossProfitGross profit売上総利益OtherFixedHomeSide CreditCloseByDivisionReportingSubtotal
OrdinaryProfitOrdinary profit経常利益OtherFixedHomeSide CreditCloseByDivisionReportingSubtotal
InterestEarnedInterest earned受取利息OtherFixedHomeSide CreditCloseByDivision
ReceiptFeeReceipt fee受取手数料OtherFixedHomeSide CreditCloseByDivision
RentalIncomeRental income受取家賃OtherFixedHomeSide CreditCloseByDivision
WageEarnedWage income賃金収入OtherFixedHomeSide CreditCloseByDivision
TaxesRevenueTax revenue租税収入OtherFixedHomeSide CreditCloseByDivision
CentralBankPaymentIncomeCentral bank payment to treasury国庫納付金収入OtherFixedHomeSide CreditCloseByDivision
SalesSales売上OtherFixedHomeSide CreditCloseByDivision
EquityInEarningsOfInvesteeEquity in earnings of investee持分法による投資利益OtherFixedHomeSide CreditCloseByDivision
NetLossNet loss当期純損失OtherFixedHomeSide CreditNoClosePeriodResult
GainOnSalesOfFixedAssetsGain on sales of fixed assets固定資産売却益OtherFixedHomeSide CreditCloseByDivision
RecoveryOfBadDebtsRecovery of bad debts written off償却債権取立益OtherFixedHomeSide CreditCloseByDivision
MiscellaneousIncomeMiscellaneous income雑益OtherFixedHomeSide CreditCloseByDivision
ReversalOfAllowanceForDoubtfulAccountsReversal of allowance for doubtful accounts貸倒引当金戻入OtherFixedHomeSide CreditCloseByDivision
ServiceRevenueService revenue役務収益OtherFixedHomeSide CreditCloseByDivision
OperatingRevenueOperating revenue営業収益OtherFixedHomeSide CreditCloseByDivision
GainOnSalesOfSecuritiesGain on sale of securities有価証券売却益OtherFixedHomeSide CreditCloseByDivision
GainOnValuationOfSecuritiesGain on valuation of securities有価証券評価益OtherFixedHomeSide CreditCloseByDivision
DividendsReceivedDividend income受取配当金OtherFixedHomeSide CreditCloseByDivision
InterestOnSecuritiesInterest on securities有価証券利息OtherFixedHomeSide CreditCloseByDivision
GainOnSalesOfInvestmentSecuritiesGain on sale of investment securities投資有価証券売却益OtherFixedHomeSide CreditCloseByDivision
InsuranceGainGain on insurance claims保険差益OtherFixedHomeSide CreditCloseByDivision
GainOnBargainPurchaseGain on bargain purchase負ののれん発生益OtherFixedHomeSide CreditCloseByDivision
ReversalOfAllowanceForRepairsReversal of provision for repairs修繕引当金戻入OtherFixedHomeSide CreditCloseByDivision
ReversalOfAllowanceForProductWarrantiesReversal of provision for warranties商品保証引当金戻入OtherFixedHomeSide CreditCloseByDivision
GainOnDonationOfFixedAssetsGain on receipt of donated non-current assets固定資産受贈益OtherFixedHomeSide CreditCloseByDivision
GainOnNationalSubsidiesGain on receipt of national subsidies国庫補助金受贈益OtherFixedHomeSide CreditCloseByDivision
GainOnConstructionGrantsGain on contribution received for construction工事負担金受贈益OtherFixedHomeSide CreditCloseByDivision
LandRentReceivedRental income from land受取地代OtherFixedHomeSide CreditCloseByDivision
SalesRebatesSales rebates売上割戻OtherFixedHomeSide DebitCloseByDivisionContraAccount
ForeignExchangeGainsForeign exchange gains為替差益OtherFixedHomeSide CreditCloseByDivision
NetLossAttributableToNCILoss attributable to non-controlling interests非支配株主に帰属する当期純損失OtherFixedHomeSide CreditNoCloseAttributionAccount, PeriodResult
SalesAllowancesSales allowances売上値引OtherFixedHomeSide DebitCloseByDivisionContraAccount
ReversalOfAllowanceForBonusesReversal of provision for bonuses賞与引当金戻入OtherFixedHomeSide CreditCloseByDivision

Expenses

ConstructorEnglish nameJapanese nameFixed/currentHome sideClosing ruleRoles
DepreciationDepreciation減価償却費OtherFixedHomeSide DebitCloseByDivision
AmortizationExpenseAmortization expense for intangibles無形固定資産償却費OtherFixedHomeSide DebitCloseByDivision
SalesCostCost of sales売上原価OtherFixedHomeSide DebitCloseByDivision
BusinessTripTravel and transportation旅費交通費OtherFixedHomeSide DebitCloseByDivision
CommutationCommunication通信費OtherFixedHomeSide DebitCloseByDivision
UtilitiesExpenseUtilities水道光熱費OtherFixedHomeSide DebitCloseByDivision
RentExpenseRent支払家賃OtherFixedHomeSide DebitCloseByDivision
AdvertisingExpenseAdvertising広告宣伝費OtherFixedHomeSide DebitCloseByDivision
DeliveryExpensesDelivery発送費OtherFixedHomeSide DebitCloseByDivision
SuppliesExpensesSupplies消耗品費OtherFixedHomeSide DebitCloseByDivision
MiscellaneousExpensesMiscellaneous雑費OtherFixedHomeSide DebitCloseByDivision
WageExpenditureWages給料OtherFixedHomeSide DebitCloseByDivision
InterestExpenseInterest expense支払利息OtherFixedHomeSide DebitCloseByDivision
TaxesExpenseTaxes租税公課OtherFixedHomeSide DebitCloseByDivision
ConsumptionExpenditureConsumption expenditure消費支出OtherFixedHomeSide DebitCloseByDivision
SubsidyExpenseSubsidy expenditure補助金支出OtherFixedHomeSide DebitCloseByDivision
CentralBankPaymentExpenseCentral bank payment to treasury国庫納付金支出OtherFixedHomeSide DebitCloseByDivision
PurchasesPurchases仕入OtherFixedHomeSide DebitCloseByDivision
NetIncomeNet income当期純利益OtherFixedHomeSide DebitNoClosePeriodResult
ProvisionForDoubtfulAccountsProvision for doubtful accounts貸倒引当金繰入OtherFixedHomeSide DebitCloseByDivision
BadDebtLossBad debt loss貸倒損失OtherFixedHomeSide DebitCloseByDivision
LossOnSalesOfFixedAssetsLoss on sales of fixed assets固定資産売却損OtherFixedHomeSide DebitCloseByDivision
LossOnSalesOfNotesReceivableLoss on sales of notes receivable手形売却損OtherFixedHomeSide DebitCloseByDivision
PaymentFeesPayment fees / fees paid支払手数料OtherFixedHomeSide DebitCloseByDivision
MiscellaneousLossMiscellaneous loss雑損OtherFixedHomeSide DebitCloseByDivision
CorporateIncomeTaxesCorporate income taxes法人税等OtherFixedHomeSide DebitCloseByDivision
CommunicationExpensesCommunication expenses通信費OtherFixedHomeSide DebitCloseByDivision
CostOfServicesCost of services役務原価OtherFixedHomeSide DebitCloseByDivision
OperatingExpensesOperating expenses営業費用OtherFixedHomeSide DebitCloseByDivision
InventoryShrinkageLossInventory shrinkage loss棚卸減耗損OtherFixedHomeSide DebitCloseByDivision
LossOnValuationOfMerchandiseValuation loss on goods商品評価損OtherFixedHomeSide DebitCloseByDivision
BonusesBonuses賞与OtherFixedHomeSide DebitCloseByDivision
RetirementBenefitExpensesRetirement benefit expenses退職給付費用OtherFixedHomeSide DebitCloseByDivision
ProvisionForRepairsProvision for repairs修繕引当金繰入OtherFixedHomeSide DebitCloseByDivision
ProvisionForBonusesProvision for bonuses賞与引当金繰入OtherFixedHomeSide DebitCloseByDivision
ProvisionForProductWarrantiesProvision for warranties商品保証引当金繰入OtherFixedHomeSide DebitCloseByDivision
ResearchAndDevelopmentExpensesResearch and development expenses研究開発費OtherFixedHomeSide DebitCloseByDivision
AmortizationOfGoodwillAmortization of goodwillのれん償却OtherFixedHomeSide DebitCloseByDivision
AmortizationOfSoftwareAmortization of softwareソフトウェア償却OtherFixedHomeSide DebitCloseByDivision
AmortizationOfPatentsAmortization of patent rights特許権償却OtherFixedHomeSide DebitCloseByDivision
LeaseExpensesLease expenses支払リース料OtherFixedHomeSide DebitCloseByDivision
IncorporationExpensesOrganization expenses創立費OtherFixedHomeSide DebitCloseByDivision
StockIssuanceCostsShare issuance costs株式交付費OtherFixedHomeSide DebitCloseByDivision
BusinessCommencementExpensesBusiness commencement expenses開業費OtherFixedHomeSide DebitCloseByDivision
DevelopmentExpensesDevelopment expenses開発費OtherFixedHomeSide DebitCloseByDivision
LossOnSalesOfElectronicallyRecordedReceivablesLoss on sale of electronically recorded monetary claims電子記録債権売却損OtherFixedHomeSide DebitCloseByDivision
LossOnSalesOfReceivablesLoss on sale of receivables債権売却損OtherFixedHomeSide DebitCloseByDivision
LossOnSalesOfSecuritiesLoss on sale of securities有価証券売却損OtherFixedHomeSide DebitCloseByDivision
LossOnValuationOfSecuritiesLoss on valuation of securities有価証券評価損OtherFixedHomeSide DebitCloseByDivision
LossOnSalesOfInvestmentSecuritiesLoss on sale of investment securities投資有価証券売却損OtherFixedHomeSide DebitCloseByDivision
LossOnFireLoss on fire火災損失OtherFixedHomeSide DebitCloseByDivision
LossOnRetirementOfFixedAssetsLoss on retirement of non-current assets固定資産除却損OtherFixedHomeSide DebitCloseByDivision
LossOnReductionOfFixedAssetsLoss on tax purpose reduction entry of non-current assets固定資産圧縮損OtherFixedHomeSide DebitCloseByDivision
AdditionalIncomeTaxesForPriorPeriodsAdditional income taxes for prior periods追徴法人税等OtherFixedHomeSide DebitCloseByDivision
RefundOfIncomeTaxesRefund of income taxes還付法人税等OtherFixedHomeSide CreditCloseByDivisionContraAccount
PurchaseRebatesPurchase rebates仕入割戻OtherFixedHomeSide CreditCloseByDivisionContraAccount
WelfareExpensesWelfare expenses福利厚生費OtherFixedHomeSide DebitCloseByDivision
MaintenanceExpensesMaintenance expenses保守費OtherFixedHomeSide DebitCloseByDivision
StatutoryWelfareExpensesLegal welfare expenses法定福利費OtherFixedHomeSide DebitCloseByDivision
LandRentPaidRent expenses on land支払地代OtherFixedHomeSide DebitCloseByDivision
InsuranceExpenseInsurance expenses保険料OtherFixedHomeSide DebitCloseByDivision
RepairsExpenseRepair expenses修繕費OtherFixedHomeSide DebitCloseByDivision
StorageExpensesStorage costs保管費OtherFixedHomeSide DebitCloseByDivision
MembershipFeesMembership fees諸会費OtherFixedHomeSide DebitCloseByDivision
ForeignExchangeLossesForeign exchange losses為替差損OtherFixedHomeSide DebitCloseByDivision
IncomeTaxesAdjustmentIncome taxes - deferred法人税等調整額OtherFixedHomeSide DebitCloseByDivision
NetIncomeAttributableToNCIProfit attributable to non-controlling interests非支配株主に帰属する当期純利益OtherFixedHomeSide DebitNoCloseAttributionAccount, PeriodResult
EntertainmentExpensesEntertainment expenses交際費OtherFixedHomeSide DebitCloseByDivision
MeetingExpensesMeeting expenses会議費OtherFixedHomeSide DebitCloseByDivision
NewspaperBooksExpensesNewspapers and books新聞図書費OtherFixedHomeSide DebitCloseByDivision
PurchaseAllowancesPurchase allowances仕入値引OtherFixedHomeSide CreditCloseByDivisionContraAccount

The tables are generated from the account registry.

Table generation code (excerpt)

accountRows
    :: Show title
    => [title]
    -> (title -> Maybe AccountSpec)
    -> (title -> Maybe AccountSemantics)
    -> AccountDivision
    -> [String]
accountRows titles lookupSpec lookupSemantics division =
    [ accountRow title spec semantics
    | title <- titles
    , Just spec <- [lookupSpec title]
    , asDivision spec == division
    , Just semantics <- [lookupSemantics title]
    ]

Tested with exchangealgebra-0.6.1.1 on 2026-11-20.

Checking a journal

The shop closes its books for January. Start with the dated withdrawal, purchase, exchange, and rent records from Journals and Transfers. Supply an opening balance and a cash sale, express the amounts in yen, and submit the journal for checking before deriving a trial balance.

Use exchangealgebra-0.6.1.1 in the project prepared in Add the package to a Stack project. Save the code blocks in their displayed order as Main.hs.

Prepare the January records

The program begins with the account-and-currency base and journal notes from Journals.

Code carried over from earlier chapters

{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}

module Main where

import ExchangeAlgebra hiding (Yen, Dollar, map)
import qualified ExchangeAlgebra.Algebra.Core as Algebra
import ExchangeAlgebra.Journal ((.|))
import qualified ExchangeAlgebra.Journal as Journal
import qualified ExchangeAlgebra.IO.Input.Admission as Admission

-- | Currency element retained in the source journal.
data Unit
    = Yen       -- ^ Japanese yen.
    | Dollar    -- ^ US dollars.
    | Unit      -- ^ Inapplicable in an entry; unrestricted in a query.
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Element Unit where
    wildcard = Unit

instance ExBaseClass (HatBase (AccountTitles, Unit)) where
    getAccountTitle (_ :< (account, _)) = account
    setAccountTitle (direction :< (_, unit)) account = direction :< (account, unit)

-- | Date and description; the example supplies valid calendar dates.
data EntryNote = EntryNote (Integer, Int, Int) String
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Journal.Note EntryNote where
    plank = EntryNote (0, 0, 0) ""

-- | One entry with account and currency elements; the alias adds no validation.
type Entry = Alg MoneyDecimal (HatBase (AccountTitles, Unit))

-- | January journal with one distinct note per transaction.
type Book = Journal.Journal EntryNote MoneyDecimal (HatBase (AccountTitles, Unit))

Keep the account-and-currency base and a note containing the date and description. Each description is distinct within its date. The check applies to the group of terms under each note. Entries with identical notes are combined before checking.

-- | Attach a January date and description after constructing all terms.
record :: Int -> String -> Entry -> Book
record day description algebra = algebra .| EntryNote (2026, 1, day) description

-- | January 1: capital paid into Bank A's savings account.
opening :: Book
opening = record 1 "Opening capital"
    (10000 .@ Not :< (Deposits, Yen)
  .+ 10000 .@ Not :< (CapitalStock, Yen))

-- | Transactions through January 30, before adjusting entries.
sourceJournal :: Book
sourceJournal = opening
    .+ record 10 "Withdrawal from Bank A"
        (3000 .@ Not :< (Cash, Yen) .+ 3000 .@ Hat :< (Deposits, Yen))
    .+ record 15 "Withdrawal from Bank A"
        (2000 .@ Not :< (Cash, Yen) .+ 2000 .@ Hat :< (Deposits, Yen))
    .+ record 20 "Purchase of goods"
        (500 .@ Not :< (Purchases, Yen) .+ 500 .@ Hat :< (Cash, Yen))
    .+ record 25 "Yen-dollar exchange"
        (1500 .@ Hat :< (Cash, Yen) .+ 10 .@ Not :< (Cash, Dollar))
    .+ record 28 "Cash sale"
        (2000 .@ Not :< (Cash, Yen) .+ 2000 .@ Not :< (Sales, Yen))
    .+ record 30 "January and February rent"
        (1200 .@ Not :< (RentExpense, Yen) .+ 1200 .@ Hat :< (Cash, Yen))

On January 1, the owner contributes 10,000 yen of capital to Bank A’s savings account: debit Deposits and credit CapitalStock. The two withdrawals leave 5,000 yen in Deposits. On January 28, sell goods for 2,000 yen in cash: debit Cash and credit Sales. Under the periodic inventory method, record the cost of the goods sold at the period end.

The January 30 rent payment initially records all 1,200 yen as an expense. Keep the 600-yen deferral as a separate January 31 adjusting entry in Adjusting entries; do not add it twice.

Express dollar cash in yen

At January 31, the 10 dollars are worth 1,500 yen at 150 yen per dollar, the same rate as on January 25. The transfer in the preprint’s Definition 9 moves a source term to a destination term with a value transformation; the unit conversion in Appendix A, Example 2, also replaces the source term. Here the triple consists of source (account, Dollar), destination (account, Yen), and value function $f(v)=150v$. Algebra.mapPosting applies this triple by replacing every matching term, while Journal.map applies the conversion separately at each note.

The accounting transfer table in Transfers works differently: mkTransferTable and transferEntries retain the source record and add its cancellation and the destination terms. The conversion here does not use that table: in exchangealgebra-0.6.1.1 it cannot express a unit conversion with different source and destination amounts, and the documented replacement for deprecated MulBy and DivBy is mapPosting for unit conversion.

-- | Express dollars in yen at 150 yen per dollar, preserving account and side.
toYen :: MoneyDecimal
      -> HatBase (AccountTitles, Unit)
      -> (MoneyDecimal, HatBase (AccountTitles, Unit))
toYen amount (direction :< (account, Dollar)) = (amount * 150, direction :< (account, Yen))
toYen amount basis = (amount, basis)

-- | Reporting representation at the January 31 rate, equal to the exchange rate.
yenJournal :: Book
yenJournal = Journal.map (Algebra.mapPosting toYen) sourceJournal

-- | Check the converted journal without changing its notes or term sequences.
acceptedJanuary :: Either String (Admission.Admitted EntryNote (HatBase (AccountTitles, Unit)))
acceptedJanuary = either (Left . show . Admission.failureErrors) Right
    (Admission.admit yenJournal)

sourceJournal retains the original currency records; yenJournal is a reporting representation that preserves notes and term detail but replaces the dollar element and amount. This is unit conversion, not an additional debit-credit entry. The check sums numerical amounts without converting currencies, so check the yen representation. With different exchange-date and closing-date rates, record the valuation difference as a foreign exchange gain or loss before closing.

Check the January journal

Admission.admit checks positive finite term amounts, concrete Hat/Not sides, accounts that some process may post, and exact equality of debit and credit totals within each note. It returns every detected violation in Left, or the unchanged journal wrapped in Admitted in Right. It does not verify dates, documentary evidence, opening balances, or the correctness of adjusting and closing procedures.

-- | Print a labeled result, retaining the library's diagnostic constructors.
printNamed :: Show a => String -> a -> IO ()
printNamed label value = putStrLn (label ++ ": " ++ show value)

-- | Stop the example on an unexpected checked failure.
require :: Show e => Either e a -> IO a
require = either (ioError . userError . show) pure

-- | Show gross debit and credit totals in yen, without netting the source.
printTotals :: Entry -> IO ()
printTotals ledger = do
    printNamed "Term totals (debit, credit)" (norm (decL ledger), norm (decR ledger))
    printNamed "Balanced" (balance ledger)
-- | Run the January procedure and print its checked results.
main :: IO ()
main = do
    accepted <- require acceptedJanuary
    let journal = Admission.admittedJournal accepted
    putStrLn "January journal admitted"
    printTotals (Journal.toAlg journal)
    let balances = bar $ Journal.toAlg journal
    printNamed "Balance totals (debit, credit)" (norm (decL balances), norm (decR balances))
    let bad = record 28 "Unbalanced sale"
            (2000 .@ Not :< (Cash, Yen) .+ 1900 .@ Not :< (Sales, Yen))
    case Admission.admit bad of
        Left failure -> printNamed "Rejected" (Admission.failureErrors failure)
        Right _ -> ioError (userError "Expected the unbalanced sale to be rejected")

Run stack exec -- ghc -Wall -Werror Main.hs -o admission-example, then run ./admission-example in your project directory. The program prints:

January journal admitted
Term totals (debit, credit): (20200,20200)
Balanced: True
Balance totals (debit, credit): (12000,12000)
Rejected: Imbalanced (EntryNote (2026,1,28) "Unbalanced sale") 2000 1900 :| []

The checked journal has equal debit and credit totals of 20,200 yen. An explicit bar of the combined record gives balance totals of 12,000 yen on each side; the checked journal itself retains the original terms. The rejected cash sale debits 2,000 yen but credits only 1,900 yen. Imbalanced identifies its note and the two totals. Correct that entry and submit it for checking again. A rejected journal yields no Admitted value.

Tested with exchangealgebra-0.6.1.1 on 2026-11-20.

Reference

Type or operationInputs and result
Admission.admit journalCheck every note; return an input error report or an Admitted journal.
Admission.admittedJournal acceptedRecover the journal without netting or changing its notes.
Admission.failureErrors failureRead input errors in ascending note order.
Algebra.mapPosting f algebraTransform each amount and base, without implicit bar or compress.

Trial balance and checks

Start from the checked January journal in Checking a journal. A trial balance collects each account’s debit and credit totals and its remaining debit or credit balance. Equal totals are necessary for double-entry bookkeeping, but an omitted balanced entry can leave them equal.

Use exchangealgebra-0.6.1.1 in the project prepared in Add the package to a Stack project. Save the code blocks in their displayed order as Main.hs.

Recover the checked records

The program begins with the records, currency conversion, journal checking, and display helpers from Checking a journal.

Code carried over from earlier chapters

{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}

module Main where

import ExchangeAlgebra hiding (Yen, Dollar, map)
import qualified ExchangeAlgebra.Algebra.Core as Algebra
import ExchangeAlgebra.Journal ((.|))
import qualified ExchangeAlgebra.Journal as Journal
import qualified ExchangeAlgebra.IO.Input.Admission as Admission
import qualified ExchangeAlgebra.Accounting.TrialBalance as TrialBalance

-- | Currency element retained in the source journal.
data Unit
    = Yen       -- ^ Japanese yen.
    | Dollar    -- ^ US dollars.
    | Unit      -- ^ Inapplicable in an entry; unrestricted in a query.
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Element Unit where
    wildcard = Unit

instance ExBaseClass (HatBase (AccountTitles, Unit)) where
    getAccountTitle (_ :< (account, _)) = account
    setAccountTitle (direction :< (_, unit)) account = direction :< (account, unit)

-- | Date and description; the example supplies valid calendar dates.
data EntryNote = EntryNote (Integer, Int, Int) String
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Journal.Note EntryNote where
    plank = EntryNote (0, 0, 0) ""

-- | One entry with account and currency elements; the alias adds no validation.
type Entry = Alg MoneyDecimal (HatBase (AccountTitles, Unit))

-- | January journal with one distinct note per transaction.
type Book = Journal.Journal EntryNote MoneyDecimal (HatBase (AccountTitles, Unit))
-- | Attach a January date and description after constructing all terms.
record :: Int -> String -> Entry -> Book
record day description algebra = algebra .| EntryNote (2026, 1, day) description

-- | January 1: capital paid into Bank A's savings account.
opening :: Book
opening = record 1 "Opening capital"
    (10000 .@ Not :< (Deposits, Yen)
  .+ 10000 .@ Not :< (CapitalStock, Yen))

-- | Transactions through January 30, before adjusting entries.
sourceJournal :: Book
sourceJournal = opening
    .+ record 10 "Withdrawal from Bank A"
        (3000 .@ Not :< (Cash, Yen) .+ 3000 .@ Hat :< (Deposits, Yen))
    .+ record 15 "Withdrawal from Bank A"
        (2000 .@ Not :< (Cash, Yen) .+ 2000 .@ Hat :< (Deposits, Yen))
    .+ record 20 "Purchase of goods"
        (500 .@ Not :< (Purchases, Yen) .+ 500 .@ Hat :< (Cash, Yen))
    .+ record 25 "Yen-dollar exchange"
        (1500 .@ Hat :< (Cash, Yen) .+ 10 .@ Not :< (Cash, Dollar))
    .+ record 28 "Cash sale"
        (2000 .@ Not :< (Cash, Yen) .+ 2000 .@ Not :< (Sales, Yen))
    .+ record 30 "January and February rent"
        (1200 .@ Not :< (RentExpense, Yen) .+ 1200 .@ Hat :< (Cash, Yen))
-- | Express dollars in yen at 150 yen per dollar, preserving account and side.
toYen :: MoneyDecimal
      -> HatBase (AccountTitles, Unit)
      -> (MoneyDecimal, HatBase (AccountTitles, Unit))
toYen amount (direction :< (account, Dollar)) = (amount * 150, direction :< (account, Yen))
toYen amount basis = (amount, basis)

-- | Reporting representation at the January 31 rate, equal to the exchange rate.
yenJournal :: Book
yenJournal = Journal.map (Algebra.mapPosting toYen) sourceJournal

-- | Check the converted journal without changing its notes or term sequences.
acceptedJanuary :: Either String (Admission.Admitted EntryNote (HatBase (AccountTitles, Unit)))
acceptedJanuary = either (Left . show . Admission.failureErrors) Right
    (Admission.admit yenJournal)
-- | Print a labeled result, retaining the library's diagnostic constructors.
printNamed :: Show a => String -> a -> IO ()
printNamed label value = putStrLn (label ++ ": " ++ show value)

-- | Stop the example on an unexpected checked failure.
require :: Show e => Either e a -> IO a
require = either (ioError . userError . show) pure

-- | Show gross debit and credit totals in yen, without netting the source.
printTotals :: Entry -> IO ()
printTotals ledger = do
    printNamed "Term totals (debit, credit)" (norm (decL ledger), norm (decR ledger))
    printNamed "Balanced" (balance ledger)

The opening contribution, the two withdrawals, the purchase, the cash sale, and the rent payment are unchanged. Dollar cash has already been expressed in yen. Recover the record with Admission.admittedJournal, then remove note keys with Journal.toAlg when calculating balances across the month. Neither operation nets terms.

Compute debit and credit totals and balances

-- | Accounts used in the shop, ordered for repeatable output including zero balances.
accounts :: [AccountTitles]
accounts = [Cash, Deposits, PrepaidExpenses, MerchandiseInventory,
            Purchases, RentExpense, Sales, CapitalStock, RetainedEarnings]

-- | Drop the currency element only after checking every term is in yen.
-- This reporting projection removes the currency element; it does not net terms.
auditLedger :: Entry -> Either String (Alg MoneyDecimal (HatBase AccountTitles))
auditLedger ledger
    | Algebra.foldEntries allYen True ledger = Right (Algebra.mapPosting dropUnit ledger)
    | otherwise = Left "Audit requires yen on every term"
  where
    allYen :: Bool -> MoneyDecimal -> HatBase (AccountTitles, Unit) -> Bool
    allYen result _ (_ :< (_, unit)) = result && unit == Yen

    dropUnit :: MoneyDecimal
             -> HatBase (AccountTitles, Unit)
             -> (MoneyDecimal, HatBase AccountTitles)
    dropUnit amount (direction :< (account, _)) = (amount, direction :< account)

-- | Print account debit and credit totals, net balances, balance totals, and accounting findings.
printTrial :: TrialBalance.TrialBalanceStage -> Entry -> IO ()
printTrial stage ledger = do
    reporting <- require (auditLedger ledger)
    let balances = TrialBalance.accountBalances reporting
        pairs :: [(MoneyDecimal, MoneyDecimal)]
        pairs = map (TrialBalance.balancePair . (`TrialBalance.balanceFor` balances)) accounts
        totals :: (MoneyDecimal, MoneyDecimal)
        totals = foldr TrialBalance.addPair (0, 0) pairs
        row :: AccountTitles -> IO ()
        row account = do
            let selected = projByAccountTitle account ledger
            printNamed (show account)
                (norm (decL selected), norm (decR selected),
                 TrialBalance.balanceFor account balances)
    putStrLn "Account: (debit turnover, credit turnover, balance)"
    mapM_ row accounts
    printNamed "Balance totals (debit, credit)" totals
    printTotals ledger
    printNamed "Findings" $ TrialBalance.trialBalanceFindings
        (TrialBalance.TrialBalanceInput reporting stage mempty [] mempty)

decL selects debit terms and decR selects credit terms, as in Definition 8; norm totals their non-negative amounts. The side depends on the account class and Hat/Not, as in Definition 7. For example, both Cash and Sales increase with Not in the cash sale, but Cash is debited and Sales is credited.

accountBalances sums each account exactly and returns a non-negative magnitude with DebitBalance, CreditBalance, or NoBalance. It computes net balances without calling bar or changing the source record. The report sums the debit and credit balance columns separately from gross term totals.

TrialBalanceInput accepts only HatBase AccountTitles. Check that every term is in yen before removing the currency element for the trial balance checks. This lossy projection removes currency information from the reporting copy; retain the account-and-currency journal as the record. Empty explanations, rules, and evidence sets mean that no such external information has been supplied.

Inspect a missing opening balance

-- | Run the January procedure and print its checked results.
main :: IO ()
main = do
    accepted <- require acceptedJanuary
    let journal = Admission.admittedJournal accepted
    printTrial TrialBalance.BeforeClosing (Journal.toAlg journal)
    let withoutOpening = Journal.filterWithNote (\note _ -> note /= EntryNote (2026, 1, 1)
            "Opening capital") journal
    incomplete <- require (Admission.admit withoutOpening)
    putStrLn "Without opening balances:"
    printTrial TrialBalance.BeforeClosing
        $ Journal.toAlg
        $ Admission.admittedJournal incomplete

Run stack exec -- ghc -Wall -Werror Main.hs -o trial-balance-example, then run ./trial-balance-example in your project directory. The program prints:

Account: (debit turnover, credit turnover, balance)
Cash: (8500,3200,DebitBalance 5300)
Deposits: (10000,5000,DebitBalance 5000)
PrepaidExpenses: (0,0,NoBalance)
MerchandiseInventory: (0,0,NoBalance)
Purchases: (500,0,DebitBalance 500)
RentExpense: (1200,0,DebitBalance 1200)
Sales: (0,2000,CreditBalance 2000)
CapitalStock: (0,10000,CreditBalance 10000)
RetainedEarnings: (0,0,NoBalance)
Balance totals (debit, credit): (12000,12000)
Term totals (debit, credit): (20200,20200)
Balanced: True
Findings: []
Without opening balances:
Account: (debit turnover, credit turnover, balance)
Cash: (8500,3200,DebitBalance 5300)
Deposits: (0,5000,CreditBalance 5000)
PrepaidExpenses: (0,0,NoBalance)
MerchandiseInventory: (0,0,NoBalance)
Purchases: (500,0,DebitBalance 500)
RentExpense: (1200,0,DebitBalance 1200)
Sales: (0,2000,CreditBalance 2000)
CapitalStock: (0,0,NoBalance)
RetainedEarnings: (0,0,NoBalance)
Balance totals (debit, credit): (7000,7000)
Term totals (debit, credit): (10200,10200)
Balanced: True
Findings: [UnexplainedAbnormalBalance Deposits Debit (CreditBalance 5000)]

With the opening contribution, Deposits has a debit balance of 5,000 yen and the balance columns each total 12,000 yen. Cash has a debit balance of 5,300 yen, including the yen equivalent of the 10 dollars. Its debit total is 8,500 yen and its credit total is 3,200 yen.

Remove the opening contribution as a whole and the journal still passes the check: the terms under each remaining note balance. Deposits then has a credit balance of 5,000 yen. UnexplainedAbnormalBalance Deposits Debit (CreditBalance 5000) reports that Deposits normally has a debit balance. Findings neither reject nor repair the journal. For these records, restore the independently confirmed opening contribution; do not invent a balancing entry merely to remove the finding.

Tested with exchangealgebra-0.6.1.1 on 2026-11-20.

Reference

Type or operationInputs and result
TrialBalance.accountBalances ledgerCompute account balances across all supplied terms.
TrialBalance.balanceFor account balancesRead an account; an absent account returns NoBalance.
TrialBalance.balancePair balanceReturn a pair ordered as debit balance, then credit balance.
TrialBalance.trialBalanceFindings inputReport structural errors, imbalance, abnormal sides, residuals, and missing evidence according to the supplied stage and rules.

Adjusting entries

At January 31, part of the rent belongs to February and some purchased goods remain unsold. Start from the checked journal in Trial balance and checks, defer the February rent, and recognize ending inventory before closing January’s revenue and expenses.

Use exchangealgebra-0.6.1.1 in the project prepared in Add the package to a Stack project. Save the code blocks in their displayed order as Main.hs.

Recover January before adjustments

The program begins with the checked records and trial-balance calculations from Trial balance and checks and the chapters before it.

Code carried over from earlier chapters

{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}

module Main where

import ExchangeAlgebra hiding (Yen, Dollar, map)
import qualified ExchangeAlgebra.Algebra.Core as Algebra
import ExchangeAlgebra.Journal ((.|))
import qualified ExchangeAlgebra.Journal as Journal
import qualified ExchangeAlgebra.IO.Input.Admission as Admission
import qualified ExchangeAlgebra.Accounting.TrialBalance as TrialBalance
import qualified ExchangeAlgebra.Accounting.Entries as Entries

-- | Currency element retained in the source journal.
data Unit
    = Yen       -- ^ Japanese yen.
    | Dollar    -- ^ US dollars.
    | Unit      -- ^ Inapplicable in an entry; unrestricted in a query.
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Element Unit where
    wildcard = Unit

instance ExBaseClass (HatBase (AccountTitles, Unit)) where
    getAccountTitle (_ :< (account, _)) = account
    setAccountTitle (direction :< (_, unit)) account = direction :< (account, unit)

-- | Date and description; the example supplies valid calendar dates.
data EntryNote = EntryNote (Integer, Int, Int) String
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Journal.Note EntryNote where
    plank = EntryNote (0, 0, 0) ""

-- | One entry with account and currency elements; the alias adds no validation.
type Entry = Alg MoneyDecimal (HatBase (AccountTitles, Unit))

-- | January journal with one distinct note per transaction.
type Book = Journal.Journal EntryNote MoneyDecimal (HatBase (AccountTitles, Unit))
-- | Attach a January date and description after constructing all terms.
record :: Int -> String -> Entry -> Book
record day description algebra = algebra .| EntryNote (2026, 1, day) description

-- | January 1: capital paid into Bank A's savings account.
opening :: Book
opening = record 1 "Opening capital"
    (10000 .@ Not :< (Deposits, Yen)
  .+ 10000 .@ Not :< (CapitalStock, Yen))

-- | Transactions through January 30, before adjusting entries.
sourceJournal :: Book
sourceJournal = opening
    .+ record 10 "Withdrawal from Bank A"
        (3000 .@ Not :< (Cash, Yen) .+ 3000 .@ Hat :< (Deposits, Yen))
    .+ record 15 "Withdrawal from Bank A"
        (2000 .@ Not :< (Cash, Yen) .+ 2000 .@ Hat :< (Deposits, Yen))
    .+ record 20 "Purchase of goods"
        (500 .@ Not :< (Purchases, Yen) .+ 500 .@ Hat :< (Cash, Yen))
    .+ record 25 "Yen-dollar exchange"
        (1500 .@ Hat :< (Cash, Yen) .+ 10 .@ Not :< (Cash, Dollar))
    .+ record 28 "Cash sale"
        (2000 .@ Not :< (Cash, Yen) .+ 2000 .@ Not :< (Sales, Yen))
    .+ record 30 "January and February rent"
        (1200 .@ Not :< (RentExpense, Yen) .+ 1200 .@ Hat :< (Cash, Yen))
-- | Express dollars in yen at 150 yen per dollar, preserving account and side.
toYen :: MoneyDecimal
      -> HatBase (AccountTitles, Unit)
      -> (MoneyDecimal, HatBase (AccountTitles, Unit))
toYen amount (direction :< (account, Dollar)) = (amount * 150, direction :< (account, Yen))
toYen amount basis = (amount, basis)

-- | Reporting representation at the January 31 rate, equal to the exchange rate.
yenJournal :: Book
yenJournal = Journal.map (Algebra.mapPosting toYen) sourceJournal

-- | Check the converted journal without changing its notes or term sequences.
acceptedJanuary :: Either String (Admission.Admitted EntryNote (HatBase (AccountTitles, Unit)))
acceptedJanuary = either (Left . show . Admission.failureErrors) Right
    (Admission.admit yenJournal)
-- | Print a labeled result, retaining the library's diagnostic constructors.
printNamed :: Show a => String -> a -> IO ()
printNamed label value = putStrLn (label ++ ": " ++ show value)

-- | Stop the example on an unexpected checked failure.
require :: Show e => Either e a -> IO a
require = either (ioError . userError . show) pure

-- | Show gross debit and credit totals in yen, without netting the source.
printTotals :: Entry -> IO ()
printTotals ledger = do
    printNamed "Term totals (debit, credit)" (norm (decL ledger), norm (decR ledger))
    printNamed "Balanced" (balance ledger)
-- | Accounts used in the shop, ordered for repeatable output including zero balances.
accounts :: [AccountTitles]
accounts = [Cash, Deposits, PrepaidExpenses, MerchandiseInventory,
            Purchases, RentExpense, Sales, CapitalStock, RetainedEarnings]

-- | Drop the currency element only after checking every term is in yen.
-- This reporting projection removes the currency element; it does not net terms.
auditLedger :: Entry -> Either String (Alg MoneyDecimal (HatBase AccountTitles))
auditLedger ledger
    | Algebra.foldEntries allYen True ledger = Right (Algebra.mapPosting dropUnit ledger)
    | otherwise = Left "Audit requires yen on every term"
  where
    allYen :: Bool -> MoneyDecimal -> HatBase (AccountTitles, Unit) -> Bool
    allYen result _ (_ :< (_, unit)) = result && unit == Yen

    dropUnit :: MoneyDecimal
             -> HatBase (AccountTitles, Unit)
             -> (MoneyDecimal, HatBase AccountTitles)
    dropUnit amount (direction :< (account, _)) = (amount, direction :< account)

-- | Print account debit and credit totals, net balances, balance totals, and accounting findings.
printTrial :: TrialBalance.TrialBalanceStage -> Entry -> IO ()
printTrial stage ledger = do
    reporting <- require (auditLedger ledger)
    let balances = TrialBalance.accountBalances reporting
        pairs :: [(MoneyDecimal, MoneyDecimal)]
        pairs = map (TrialBalance.balancePair . (`TrialBalance.balanceFor` balances)) accounts
        totals :: (MoneyDecimal, MoneyDecimal)
        totals = foldr TrialBalance.addPair (0, 0) pairs
        row :: AccountTitles -> IO ()
        row account = do
            let selected = projByAccountTitle account ledger
            printNamed (show account)
                (norm (decL selected), norm (decR selected),
                 TrialBalance.balanceFor account balances)
    putStrLn "Account: (debit turnover, credit turnover, balance)"
    mapM_ row accounts
    printNamed "Balance totals (debit, credit)" totals
    printTotals ledger
    printNamed "Findings" $ TrialBalance.trialBalanceFindings
        (TrialBalance.TrialBalanceInput reporting stage mempty [] mempty)

Defer rent and count inventory

The rent transfer moves 600 yen from RentExpense to PrepaidExpenses. It is an adjusting entry: debit PrepaidExpenses and credit RentExpense on January 31, leaving 600 yen of rent expense for January. Generate this entry from the unadjusted ledger once.

The shop has no beginning merchandise inventory, purchases goods for 500 yen during January, and counts ending inventory worth 200 yen at cost. Under the periodic three-account method, cost of goods sold is beginning inventory plus purchases less ending inventory: $0+500-200=300$ yen. Debit MerchandiseInventory and credit Purchases for 200 yen; the Purchases balance then represents cost of goods sold.

-- | January 31: defer February's half of the rent, using the rent transfer table.
rentAdjustment :: Entry -> Either String Entry
rentAdjustment ledger = do
    table <- either (Left . show) Right $ mkTransferTable
        [(RentExpense, (.#)) .-> (PrepaidExpenses, (.#)) |% Portion 1 2]
    either (Left . show) Right (transferEntries table ledger)

-- | Keep the currency element when building the periodic inventory adjustment.
yenBase :: Entries.MkBase (HatBase (AccountTitles, Unit))
yenBase direction account = direction :< (account, Yen)

-- | No beginning inventory; the January 31 physical count is worth 200 yen at cost.
inventoryAdjustment :: Entry
inventoryAdjustment = Entries.cogsAdjustmentEntries yenBase 0 200

-- | Add adjustments under distinct notes and check the resulting journal again.
adjustedJanuary :: Book -> Either String Book
adjustedJanuary journal = do
    rent <- rentAdjustment (Journal.toAlg journal)
    let adjusted :: Book
        adjusted = journal
                .+ record 31 "Defer February rent" rent
                .+ record 31 "Ending inventory" inventoryAdjustment
    admitted <- either (Left . show . Admission.failureErrors) Right (Admission.admit adjusted)
    pure (Admission.admittedJournal admitted)

Use Entries.cogsAdjustmentEntries with a MkBase that fills in Yen, because the entry builder accepts the existing account-and-currency base while retaining all its elements. Its arguments are the beginning and ending inventory amounts, not the purchases total. A zero beginning inventory produces no zero-valued terms. The builder returns only additional terms, without implicit bar or compress; attach a note and add them to the journal with .+.

Check and inspect the adjusted journal

-- | Run the January procedure and print its checked results.
main :: IO ()
main = do
    accepted <- require acceptedJanuary
    let journal = Admission.admittedJournal accepted
    rent <- require (rentAdjustment (Journal.toAlg journal))
    printNamed "Rent adjustment" rent
    printNamed "Inventory adjustment" inventoryAdjustment
    adjusted <- require (adjustedJanuary journal)
    printTrial TrialBalance.BeforeClosing (Journal.toAlg adjusted)

Run stack exec -- ghc -Wall -Werror Main.hs -o adjustment-example, then run ./adjustment-example in your project directory. The program prints:

Rent adjustment: 600:@Hat:<(RentExpense,Yen) .+ 600:@Not:<(PrepaidExpenses,Yen)
Inventory adjustment: 200:@Hat:<(Purchases,Yen) .+ 200:@Not:<(MerchandiseInventory,Yen)
Account: (debit turnover, credit turnover, balance)
Cash: (8500,3200,DebitBalance 5300)
Deposits: (10000,5000,DebitBalance 5000)
PrepaidExpenses: (600,0,DebitBalance 600)
MerchandiseInventory: (200,0,DebitBalance 200)
Purchases: (500,200,DebitBalance 300)
RentExpense: (1200,600,DebitBalance 600)
Sales: (0,2000,CreditBalance 2000)
CapitalStock: (0,10000,CreditBalance 10000)
RetainedEarnings: (0,0,NoBalance)
Balance totals (debit, credit): (12000,12000)
Term totals (debit, credit): (21000,21000)
Balanced: True
Findings: []

The rent and inventory adjustments remain separately selectable under their January 31 notes. Checking the journal again checks their debit-credit equality along with the original entries. The adjusted trial balance has PrepaidExpenses of 600 yen, MerchandiseInventory of 200 yen, Purchases of 300 yen, and RentExpense of 600 yen. Balance totals remain 12,000 yen on each side; gross term totals increase to 21,000 yen because the added entries remain in the record.

Tested with exchangealgebra-0.6.1.1 on 2026-11-20.

Reference

Type or operationInputs and result
Entries.MkBase bA function from Hat/Not and account title to the chosen base.
Entries.cogsAdjustmentEntries mk beginning endingReturn the periodic inventory adjustment; supply non-negative finite amounts in the same unit.
transferEntries table ledgerReturn the additional rent reclassification entry, or a checked transfer error.

Closing entries

Prepare January’s closing entries after the rent and inventory adjustments in Adjusting entries. Sales of 2,000 yen less cost of goods sold of 300 yen and rent expense of 600 yen give a profit of 1,100 yen. Transfer the revenue and expense balances to retained earnings, the equity account that accumulates undistributed profits.

Use exchangealgebra-0.6.1.1 in the project prepared in Add the package to a Stack project. Save the code blocks in their displayed order as Main.hs.

Recover the adjusted journal

The program begins with the code from Adjusting entries and the chapters before it.

Code carried over from earlier chapters

{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}

module Main where

import ExchangeAlgebra hiding (Yen, Dollar, map)
import qualified ExchangeAlgebra.Algebra.Core as Algebra
import ExchangeAlgebra.Journal ((.|))
import qualified ExchangeAlgebra.Journal as Journal
import qualified ExchangeAlgebra.IO.Input.Admission as Admission
import qualified ExchangeAlgebra.Accounting.TrialBalance as TrialBalance
import qualified ExchangeAlgebra.Accounting.Entries as Entries
import qualified ExchangeAlgebra.Accounting.Closing as Closing

-- | Currency element retained in the source journal.
data Unit
    = Yen       -- ^ Japanese yen.
    | Dollar    -- ^ US dollars.
    | Unit      -- ^ Inapplicable in an entry; unrestricted in a query.
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Element Unit where
    wildcard = Unit

instance ExBaseClass (HatBase (AccountTitles, Unit)) where
    getAccountTitle (_ :< (account, _)) = account
    setAccountTitle (direction :< (_, unit)) account = direction :< (account, unit)

-- | Date and description; the example supplies valid calendar dates.
data EntryNote = EntryNote (Integer, Int, Int) String
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Journal.Note EntryNote where
    plank = EntryNote (0, 0, 0) ""

-- | One entry with account and currency elements; the alias adds no validation.
type Entry = Alg MoneyDecimal (HatBase (AccountTitles, Unit))

-- | January journal with one distinct note per transaction.
type Book = Journal.Journal EntryNote MoneyDecimal (HatBase (AccountTitles, Unit))
-- | Attach a January date and description after constructing all terms.
record :: Int -> String -> Entry -> Book
record day description algebra = algebra .| EntryNote (2026, 1, day) description

-- | January 1: capital paid into Bank A's savings account.
opening :: Book
opening = record 1 "Opening capital"
    (10000 .@ Not :< (Deposits, Yen)
  .+ 10000 .@ Not :< (CapitalStock, Yen))

-- | Transactions through January 30, before adjusting entries.
sourceJournal :: Book
sourceJournal = opening
    .+ record 10 "Withdrawal from Bank A"
        (3000 .@ Not :< (Cash, Yen) .+ 3000 .@ Hat :< (Deposits, Yen))
    .+ record 15 "Withdrawal from Bank A"
        (2000 .@ Not :< (Cash, Yen) .+ 2000 .@ Hat :< (Deposits, Yen))
    .+ record 20 "Purchase of goods"
        (500 .@ Not :< (Purchases, Yen) .+ 500 .@ Hat :< (Cash, Yen))
    .+ record 25 "Yen-dollar exchange"
        (1500 .@ Hat :< (Cash, Yen) .+ 10 .@ Not :< (Cash, Dollar))
    .+ record 28 "Cash sale"
        (2000 .@ Not :< (Cash, Yen) .+ 2000 .@ Not :< (Sales, Yen))
    .+ record 30 "January and February rent"
        (1200 .@ Not :< (RentExpense, Yen) .+ 1200 .@ Hat :< (Cash, Yen))
-- | Express dollars in yen at 150 yen per dollar, preserving account and side.
toYen :: MoneyDecimal
      -> HatBase (AccountTitles, Unit)
      -> (MoneyDecimal, HatBase (AccountTitles, Unit))
toYen amount (direction :< (account, Dollar)) = (amount * 150, direction :< (account, Yen))
toYen amount basis = (amount, basis)

-- | Reporting representation at the January 31 rate, equal to the exchange rate.
yenJournal :: Book
yenJournal = Journal.map (Algebra.mapPosting toYen) sourceJournal

-- | Check the converted journal without changing its notes or term sequences.
acceptedJanuary :: Either String (Admission.Admitted EntryNote (HatBase (AccountTitles, Unit)))
acceptedJanuary = either (Left . show . Admission.failureErrors) Right
    (Admission.admit yenJournal)
-- | Print a labeled result, retaining the library's diagnostic constructors.
printNamed :: Show a => String -> a -> IO ()
printNamed label value = putStrLn (label ++ ": " ++ show value)

-- | Stop the example on an unexpected checked failure.
require :: Show e => Either e a -> IO a
require = either (ioError . userError . show) pure

-- | Show gross debit and credit totals in yen, without netting the source.
printTotals :: Entry -> IO ()
printTotals ledger = do
    printNamed "Term totals (debit, credit)" (norm (decL ledger), norm (decR ledger))
    printNamed "Balanced" (balance ledger)
-- | Accounts used in the shop, ordered for repeatable output including zero balances.
accounts :: [AccountTitles]
accounts = [Cash, Deposits, PrepaidExpenses, MerchandiseInventory,
            Purchases, RentExpense, Sales, CapitalStock, RetainedEarnings]

-- | Drop the currency element only after checking every term is in yen.
-- This reporting projection removes the currency element; it does not net terms.
auditLedger :: Entry -> Either String (Alg MoneyDecimal (HatBase AccountTitles))
auditLedger ledger
    | Algebra.foldEntries allYen True ledger = Right (Algebra.mapPosting dropUnit ledger)
    | otherwise = Left "Audit requires yen on every term"
  where
    allYen :: Bool -> MoneyDecimal -> HatBase (AccountTitles, Unit) -> Bool
    allYen result _ (_ :< (_, unit)) = result && unit == Yen

    dropUnit :: MoneyDecimal
             -> HatBase (AccountTitles, Unit)
             -> (MoneyDecimal, HatBase AccountTitles)
    dropUnit amount (direction :< (account, _)) = (amount, direction :< account)

-- | Print account debit and credit totals, net balances, balance totals, and accounting findings.
printTrial :: TrialBalance.TrialBalanceStage -> Entry -> IO ()
printTrial stage ledger = do
    reporting <- require (auditLedger ledger)
    let balances = TrialBalance.accountBalances reporting
        pairs :: [(MoneyDecimal, MoneyDecimal)]
        pairs = map (TrialBalance.balancePair . (`TrialBalance.balanceFor` balances)) accounts
        totals :: (MoneyDecimal, MoneyDecimal)
        totals = foldr TrialBalance.addPair (0, 0) pairs
        row :: AccountTitles -> IO ()
        row account = do
            let selected = projByAccountTitle account ledger
            printNamed (show account)
                (norm (decL selected), norm (decR selected),
                 TrialBalance.balanceFor account balances)
    putStrLn "Account: (debit turnover, credit turnover, balance)"
    mapM_ row accounts
    printNamed "Balance totals (debit, credit)" totals
    printTotals ledger
    printNamed "Findings" $ TrialBalance.trialBalanceFindings
        (TrialBalance.TrialBalanceInput reporting stage mempty [] mempty)
-- | January 31: defer February's half of the rent, using the rent transfer table.
rentAdjustment :: Entry -> Either String Entry
rentAdjustment ledger = do
    table <- either (Left . show) Right $ mkTransferTable
        [(RentExpense, (.#)) .-> (PrepaidExpenses, (.#)) |% Portion 1 2]
    either (Left . show) Right (transferEntries table ledger)

-- | Keep the currency element when building the periodic inventory adjustment.
yenBase :: Entries.MkBase (HatBase (AccountTitles, Unit))
yenBase direction account = direction :< (account, Yen)

-- | No beginning inventory; the January 31 physical count is worth 200 yen at cost.
inventoryAdjustment :: Entry
inventoryAdjustment = Entries.cogsAdjustmentEntries yenBase 0 200

-- | Add adjustments under distinct notes and check the resulting journal again.
adjustedJanuary :: Book -> Either String Book
adjustedJanuary journal = do
    rent <- rentAdjustment (Journal.toAlg journal)
    let adjusted :: Book
        adjusted = journal
                .+ record 31 "Defer February rent" rent
                .+ record 31 "Ending inventory" inventoryAdjustment
    admitted <- either (Left . show . Admission.failureErrors) Right (Admission.admit adjusted)
    pure (Admission.admittedJournal admitted)

Generate closing entries

Closing.closingEntries reads the ledger through the closing date and returns only additional entries. For each eligible account-and-currency base, it computes the exact net, reverses that balance, and adds a term with the matching amount to RetainedEarnings. Other elements of the base are preserved. It sums source balances internally, without calling bar; separate contributions from different expense and revenue accounts remain separate terms.

See Account titles and their attributes for the closing rule and division used to select accounts for transfer to RetainedEarnings.

-- | Generate additional closing entries from the adjusted ledger, then check the resulting journal.
closedJanuary :: Book -> Either String Book
closedJanuary journal = do
    additions <- either (Left . show) Right (Closing.closingEntries (Journal.toAlg journal))
    let closed :: Book
        closed = journal .+ record 31 "Close January" additions
    admitted <- either (Left . show . Admission.failureErrors) Right (Admission.admit closed)
    pure (Admission.admittedJournal admitted)

For Sales, debit 2,000 yen by reversing its Not balance with Hat, and credit RetainedEarnings. For Purchases and RentExpense, credit 300 and 600 yen to cancel their debit balances, and debit RetainedEarnings for the same amounts. RetainedEarnings therefore has credits of 2,000 yen and debits of 900 yen, leaving a credit balance of 1,100 yen. Japanese bookkeeping textbooks collect revenue and expenses in an income summary account before transferring the result to retained earnings, whereas exchangealgebra-0.6.1.1’s closingEntries transfers those balances directly to RetainedEarnings, producing the same final balances.

Inspect the post-closing trial balance

-- | Run the January procedure and print its checked results.
main :: IO ()
main = do
    accepted <- require acceptedJanuary
    adjusted <- require
              $ adjustedJanuary
              $ Admission.admittedJournal accepted
    additions <- require
               $ Closing.closingEntries
               $ Journal.toAlg adjusted
    printNamed "Closing entries" additions
    closed <- require (closedJanuary adjusted)
    printTrial TrialBalance.AfterClosing (Journal.toAlg closed)
    printNamed "Closing again" (Closing.closingEntries (Journal.toAlg closed))

Run stack exec -- ghc -Wall -Werror Main.hs -o closing-example, then run ./closing-example in your project directory. The program prints:

Closing entries: 300:@Hat:<(RetainedEarnings,Yen) .+ 600:@Hat:<(RetainedEarnings,Yen) .+ 2000:@Not:<(RetainedEarnings,Yen) .+ 600:@Hat:<(RentExpense,Yen) .+ 300:@Hat:<(Purchases,Yen) .+ 2000:@Hat:<(Sales,Yen)
Account: (debit turnover, credit turnover, balance)
Cash: (8500,3200,DebitBalance 5300)
Deposits: (10000,5000,DebitBalance 5000)
PrepaidExpenses: (600,0,DebitBalance 600)
MerchandiseInventory: (200,0,DebitBalance 200)
Purchases: (500,500,NoBalance)
RentExpense: (1200,1200,NoBalance)
Sales: (2000,2000,NoBalance)
CapitalStock: (0,10000,CreditBalance 10000)
RetainedEarnings: (900,2000,CreditBalance 1100)
Balance totals (debit, credit): (11100,11100)
Term totals (debit, credit): (23900,23900)
Balanced: True
Findings: []
Closing again: Right 0

Sales, Purchases, and RentExpense each have NoBalance; their original and closing terms remain in the columns for debit and credit totals. Cash, Deposits, PrepaidExpenses, and MerchandiseInventory total 11,100 yen on the debit side. CapitalStock of 10,000 yen and RetainedEarnings of 1,100 yen total 11,100 yen on the credit side. Only assets and equity have balances in this example; there are no liabilities.

Check with AfterClosing so residual revenue and expense balances are findings. Checking the journal again alone cannot establish that closing was complete. The empty findings and Closing again: Right 0 confirm that no eligible balance remains for another closing entry. Keep the checked closed journal with all dated entries; a balance report is not a replacement for that record.

Tested with exchangealgebra-0.6.1.1 on 2026-11-20.

Reference

Type or operationInputs and result
Closing.closingEntries ledgerReturn additional entries to RetainedEarnings, or Left for an invalid eligible balance.
TrialBalance.AfterClosingCheck the post-closing trial balance, including unclosed revenue and expense accounts.
additions .| note and journal .+ closingJournalAttach a closing note to the additions, then add them to the adjusted journal.

Financial statements

The shop needs an income statement for January and a balance sheet at January 31. The income statement measures the revenue and expenses for the month. The balance sheet shows the assets, liabilities, and equity at the end of the month.

Use exchangealgebra-0.6.1.1 in the project prepared in Add the package to a Stack project. Save the Haskell blocks in their displayed order as Main.hs.

Select the January balances

Start with the records from Closing entries. Prepare the income statement from the balances after the rent and inventory adjustments and before recording closing entries. Keep the journal with the closing entries for the balance sheet. Both reports use HatBase AccountTitles. The conversion to that base checks that every term is in yen before removing the currency element.

Code carried over from earlier chapters

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}

module Main where

import ExchangeAlgebra hiding (Yen, Dollar, map)
import qualified ExchangeAlgebra.Algebra.Core as Algebra
import ExchangeAlgebra.Journal ((.|))
import qualified ExchangeAlgebra.Journal as Journal
import qualified ExchangeAlgebra.IO.Input.Admission as Admission
import qualified ExchangeAlgebra.Accounting.Entries as Entries
import qualified ExchangeAlgebra.Accounting.Closing as Closing

import qualified ExchangeAlgebra.Accounting.TrialBalance as TrialBalance
import qualified ExchangeAlgebra.Accounting.Statements as Statements

-- | Currency element retained in the source journal.
data Unit
    = Yen       -- ^ Japanese yen.
    | Dollar    -- ^ US dollars.
    | Unit      -- ^ Inapplicable in an entry; unrestricted in a query.
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Element Unit where
    wildcard = Unit

instance ExBaseClass (HatBase (AccountTitles, Unit)) where
    getAccountTitle (_ :< (account, _)) = account
    setAccountTitle (direction :< (_, unit)) account = direction :< (account, unit)

-- | Date and description; the example supplies valid calendar dates.
data EntryNote = EntryNote (Integer, Int, Int) String
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Journal.Note EntryNote where
    plank = EntryNote (0, 0, 0) ""

-- | One entry with account and currency elements; the alias adds no validation.
type Entry = Alg MoneyDecimal (HatBase (AccountTitles, Unit))

-- | January journal with one distinct note per transaction.
type Book = Journal.Journal EntryNote MoneyDecimal (HatBase (AccountTitles, Unit))
-- | Attach a January date and description after constructing all terms.
record :: Int -> String -> Entry -> Book
record day description algebra = algebra .| EntryNote (2026, 1, day) description

-- | January 1: capital paid into Bank A's savings account.
opening :: Book
opening = record 1 "Opening capital"
    (10000 .@ Not :< (Deposits, Yen)
  .+ 10000 .@ Not :< (CapitalStock, Yen))

-- | Transactions through January 30, before adjusting entries.
sourceJournal :: Book
sourceJournal = opening
    .+ record 10 "Withdrawal from Bank A"
        (3000 .@ Not :< (Cash, Yen) .+ 3000 .@ Hat :< (Deposits, Yen))
    .+ record 15 "Withdrawal from Bank A"
        (2000 .@ Not :< (Cash, Yen) .+ 2000 .@ Hat :< (Deposits, Yen))
    .+ record 20 "Purchase of goods"
        (500 .@ Not :< (Purchases, Yen) .+ 500 .@ Hat :< (Cash, Yen))
    .+ record 25 "Yen-dollar exchange"
        (1500 .@ Hat :< (Cash, Yen) .+ 10 .@ Not :< (Cash, Dollar))
    .+ record 28 "Cash sale"
        (2000 .@ Not :< (Cash, Yen) .+ 2000 .@ Not :< (Sales, Yen))
    .+ record 30 "January and February rent"
        (1200 .@ Not :< (RentExpense, Yen) .+ 1200 .@ Hat :< (Cash, Yen))
-- | Express dollars in yen at 150 yen per dollar, preserving account and side.
toYen :: MoneyDecimal
      -> HatBase (AccountTitles, Unit)
      -> (MoneyDecimal, HatBase (AccountTitles, Unit))
toYen amount (direction :< (account, Dollar)) = (amount * 150, direction :< (account, Yen))
toYen amount basis = (amount, basis)

-- | Reporting representation at the January 31 rate, equal to the exchange rate.
yenJournal :: Book
yenJournal = Journal.map (Algebra.mapPosting toYen) sourceJournal

-- | Check the converted journal without changing its notes or term sequences.
acceptedJanuary :: Either String (Admission.Admitted EntryNote (HatBase (AccountTitles, Unit)))
acceptedJanuary = either (Left . show . Admission.failureErrors) Right
    (Admission.admit yenJournal)
-- | Print a labeled result, retaining the library's diagnostic constructors.
printNamed :: Show a => String -> a -> IO ()
printNamed label value = putStrLn (label ++ ": " ++ show value)

-- | Stop the example on an unexpected checked failure.
require :: Show e => Either e a -> IO a
require = either (ioError . userError . show) pure

-- | Drop the currency element only after checking every term is in yen.
-- This reporting projection removes the currency element; it does not net terms.
auditLedger :: Entry -> Either String (Alg MoneyDecimal (HatBase AccountTitles))
auditLedger ledger
    | Algebra.foldEntries allYen True ledger = Right (Algebra.mapPosting dropUnit ledger)
    | otherwise = Left "Audit requires yen on every term"
  where
    allYen :: Bool -> MoneyDecimal -> HatBase (AccountTitles, Unit) -> Bool
    allYen result _ (_ :< (_, unit)) = result && unit == Yen

    dropUnit :: MoneyDecimal
             -> HatBase (AccountTitles, Unit)
             -> (MoneyDecimal, HatBase AccountTitles)
    dropUnit amount (direction :< (account, _)) = (amount, direction :< account)
-- | January 31: defer February's half of the rent, using the rent transfer table.
rentAdjustment :: Entry -> Either String Entry
rentAdjustment ledger = do
    table <- either (Left . show) Right $ mkTransferTable
        [(RentExpense, (.#)) .-> (PrepaidExpenses, (.#)) |% Portion 1 2]
    either (Left . show) Right (transferEntries table ledger)

-- | Keep the currency element when building the periodic inventory adjustment.
yenBase :: Entries.MkBase (HatBase (AccountTitles, Unit))
yenBase direction account = direction :< (account, Yen)

-- | No beginning inventory; the January 31 physical count is worth 200 yen at cost.
inventoryAdjustment :: Entry
inventoryAdjustment = Entries.cogsAdjustmentEntries yenBase 0 200

-- | Add adjustments under distinct notes and check the resulting journal again.
adjustedJanuary :: Book -> Either String Book
adjustedJanuary journal = do
    rent <- rentAdjustment (Journal.toAlg journal)
    let adjusted :: Book
        adjusted = journal
                .+ record 31 "Defer February rent" rent
                .+ record 31 "Ending inventory" inventoryAdjustment
    admitted <- either (Left . show . Admission.failureErrors) Right (Admission.admit adjusted)
    pure (Admission.admittedJournal admitted)
-- | Generate additional closing entries from the adjusted ledger, then check the resulting journal.
closedJanuary :: Book -> Either String Book
closedJanuary journal = do
    additions <- either (Left . show) Right (Closing.closingEntries (Journal.toAlg journal))
    let closed :: Book
        closed = journal .+ record 31 "Close January" additions
    admitted <- either (Left . show . Admission.failureErrors) Right (Admission.admit closed)
    pure (Admission.admittedJournal admitted)

Build the income statement

Pass the adjusted ledger to Statements.present with BeforeClosing. jcciSecondGradeContext Standalone starts with the Japanese GAAP presentation context for one entity. Choose CanonicalEnglish for English display labels. The presentation classifies the lines into sections such as revenue and expenses.

After the periodic inventory adjustment, the 300-yen balance of Purchases represents the cost of goods sold. Use PresentationRelabel to display that balance under SalesCost. The relabeling applies to the statement. The adjusted journal still carries the balance under Purchases.

periodResultOf computes the difference between revenue and expenses as a reporting projection. PeriodResult distinguishes profit, loss, and break-even, with a nonnegative magnitude for profit or loss. present also produces a period-result subtotal from the before-closing ledger. Both operations accumulate balances internally and leave the terms intact.

-- | Choose English labels for the shop's standalone statements.
context :: Statements.ReportingContext MoneyDecimal
context = (Statements.jcciSecondGradeContext Statements.Standalone)
    { Statements._presentationProfile = Statements.CanonicalEnglish }

-- | Present the adjusted Purchases balance under the cost-of-sales title.
incomeContext :: Statements.ReportingContext MoneyDecimal
incomeContext = context
    { Statements._presentationRelabels =
        [Statements.PresentationRelabel Purchases SalesCost "Periodic inventory adjustment"]
    }

-- | Use the adjusted ledger to retain January's revenue and expense balances.
printIncomeStatement :: Alg MoneyDecimal (HatBase AccountTitles) -> IO ()
printIncomeStatement ledger = do
    let stage = TrialBalance.BeforeClosing
    result <- require (Statements.periodResultOf stage ledger)
    statement <- require (Statements.present incomeContext stage ledger)
    mapM_ printLine
        [ line
        | section <- [Statements.RevenueSection, Statements.ExpenseSection]
        , line <- Statements._statementLines statement
        , Statements._lineSection line == section
        ]
    printNamed "Period result" result

Build the balance sheet

Present the closed ledger with AfterClosing. The January result is already in RetainedEarnings. The balance sheet uses the asset, liability, and equity sections. The totals in the program sum the displayed magnitudes for the shop, whose balances are on their normal sides and have no deduction lines.

-- | Print the balance-sheet lines and totals for this example.
printBalanceSheet :: Statements.FinancialStatements MoneyDecimal -> IO ()
printBalanceSheet statements = do
    let lines' = Statements._statementLines statements
        inSections sections =
            [ line | section <- sections
                   , line <- lines'
                   , Statements._lineSection line == section
            ]
        assets = inSections [Statements.CurrentAssetsSection, Statements.NoncurrentAssetsSection]
        liabilitiesAndEquity = inSections
            [ Statements.CurrentLiabilitiesSection
            , Statements.NoncurrentLiabilitiesSection
            , Statements.EquitySection
            ]
    mapM_ printLine assets
    printNamed "Total assets" (sum (map Statements._lineAmount assets))
    mapM_ printLine liabilitiesAndEquity
    printNamed "Total liabilities and equity"
        (sum (map Statements._lineAmount liabilitiesAndEquity))

-- | Keep the displayed section, account label, side, and magnitude visible.
printLine :: Statements.StatementLine MoneyDecimal -> IO ()
printLine line = putStrLn $ unwords
    [ show (Statements._lineSection line)
    , show (Statements._lineLabel line)
    , show (Statements._lineSide line)
    , showValue (Statements._lineAmount line)
    ]

Inspect both statements

main :: IO ()
main = do
    accepted <- require acceptedJanuary
    adjusted <- require (adjustedJanuary (Admission.admittedJournal accepted))
    beforeClosing <- require (auditLedger (Journal.toAlg adjusted))
    putStrLn "Income statement for January (yen)"
    printIncomeStatement beforeClosing

    closed <- require (closedJanuary adjusted)
    afterClosing <- require (auditLedger (Journal.toAlg closed))
    statement <- require (Statements.present context TrialBalance.AfterClosing afterClosing)
    putStrLn "\nBalance sheet at January 31 (yen)"
    printBalanceSheet statement

In your project directory, run stack exec -- ghc -Wall -Werror Main.hs -o statements-example, then run ./statements-example.

Income statement for January (yen)
RevenueSection "Sales" Credit 2000
ExpenseSection "Cost of sales" Debit 300
ExpenseSection "Rent" Debit 600
Period result: PeriodProfit 1100

Balance sheet at January 31 (yen)
CurrentAssetsSection "Cash" Debit 5300
CurrentAssetsSection "Savings deposits" Debit 5000
CurrentAssetsSection "Merchandise inventory" Debit 200
CurrentAssetsSection "Prepaid expenses" Debit 600
Total assets: 11100
EquitySection "Capital stock" Credit 10000
EquitySection "Retained earnings" Credit 1100
Total liabilities and equity: 11100

Sales of 2,000 yen less cost of goods sold of 300 yen and rent of 600 yen leave net income of 1,100 yen. At January 31, assets total 11,100 yen. Liabilities are zero, and capital stock of 10,000 yen plus retained earnings of 1,100 yen also total 11,100 yen.

Tested with exchangealgebra-0.6.1.1 on 2026-11-20.

Reference

Type or operationInputs and result
present context stage ledgerPrepare statement lines, subtotals, and presentation events. BeforeClosing includes the period result. Use trialBalanceFindings separately to inspect accounting findings.
jcciSecondGradeContext scope and PresentationProfileStart with the JCCI grade-2 profile. Set _presentationProfile to CanonicalJapanese or CanonicalEnglish to use canonical labels.
ReportingContextSupply reporting instructions such as PresentationRelabel or PresentationAllocation. An allocation splits an asset or liability balance between current and noncurrent sections and requires evidence.
periodResultOf stage ledgerDerive PeriodProfit, PeriodLoss, or PeriodBreakEven from a before-closing ledger. AfterClosing returns MetricNotAvailableAtStage.
defaultPresentationGrouping and presentGroupsFor group-based displays, pass the default groups and gross debit and credit totals by title to presentGroups. To change group membership or deductions, supply your own list of PresentationGroupDef values. This operation is separate from the sections produced by present.

Consolidation

On February 1, the shop uses 3,000 yen from its bank deposits to form a wholly owned subsidiary. Prepare an opening consolidated balance sheet at that date from the two companies’ trial balances. A consolidation worksheet keeps the two source balances and the group adjustments (WorksheetAdjustment) as separate inputs.

Use exchangealgebra-0.6.1.1 in the project prepared in Add the package to a Stack project. Save the Haskell blocks in their displayed order as Main.hs.

Prepare the two trial balances

Carry forward the shop’s January balance-sheet amounts from Build the balance sheet. The program checks that the January ledger is in yen before dropping the currency element. Both February entries use the resulting reporting base, HatBase AccountTitles, with amounts in yen.

Code carried over from earlier chapters

{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}

module Main where

import Control.Monad (unless)
import Data.List.NonEmpty (NonEmpty((:|)))

import ExchangeAlgebra hiding (Yen, Dollar, map)
import qualified ExchangeAlgebra.Algebra.Core as Algebra
import ExchangeAlgebra.Journal ((.|))
import qualified ExchangeAlgebra.Journal as Journal
import qualified ExchangeAlgebra.IO.Input.Admission as Admission
import qualified ExchangeAlgebra.Accounting.Entries as Entries
import qualified ExchangeAlgebra.Accounting.Closing as Closing

import qualified ExchangeAlgebra.Accounting.TrialBalance as TrialBalance
import qualified ExchangeAlgebra.Accounting.Statements as Statements
import qualified ExchangeAlgebra.Accounting.Consolidation as Consolidation

-- | Currency element retained in the source journal.
data Unit
    = Yen       -- ^ Japanese yen.
    | Dollar    -- ^ US dollars.
    | Unit      -- ^ Inapplicable in an entry; unrestricted in a query.
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Element Unit where
    wildcard = Unit

instance ExBaseClass (HatBase (AccountTitles, Unit)) where
    getAccountTitle (_ :< (account, _)) = account
    setAccountTitle (direction :< (_, unit)) account = direction :< (account, unit)

-- | Date and description; the example supplies valid calendar dates.
data EntryNote = EntryNote (Integer, Int, Int) String
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Journal.Note EntryNote where
    plank = EntryNote (0, 0, 0) ""

-- | One entry with account and currency elements; the alias adds no validation.
type Entry = Alg MoneyDecimal (HatBase (AccountTitles, Unit))

-- | January journal with one distinct note per transaction.
type Book = Journal.Journal EntryNote MoneyDecimal (HatBase (AccountTitles, Unit))
-- | Attach a January date and description after constructing all terms.
record :: Int -> String -> Entry -> Book
record day description algebra = algebra .| EntryNote (2026, 1, day) description

-- | January 1: capital paid into Bank A's savings account.
opening :: Book
opening = record 1 "Opening capital"
    (10000 .@ Not :< (Deposits, Yen)
  .+ 10000 .@ Not :< (CapitalStock, Yen))

-- | Transactions through January 30, before adjusting entries.
sourceJournal :: Book
sourceJournal = opening
    .+ record 10 "Withdrawal from Bank A"
        (3000 .@ Not :< (Cash, Yen) .+ 3000 .@ Hat :< (Deposits, Yen))
    .+ record 15 "Withdrawal from Bank A"
        (2000 .@ Not :< (Cash, Yen) .+ 2000 .@ Hat :< (Deposits, Yen))
    .+ record 20 "Purchase of goods"
        (500 .@ Not :< (Purchases, Yen) .+ 500 .@ Hat :< (Cash, Yen))
    .+ record 25 "Yen-dollar exchange"
        (1500 .@ Hat :< (Cash, Yen) .+ 10 .@ Not :< (Cash, Dollar))
    .+ record 28 "Cash sale"
        (2000 .@ Not :< (Cash, Yen) .+ 2000 .@ Not :< (Sales, Yen))
    .+ record 30 "January and February rent"
        (1200 .@ Not :< (RentExpense, Yen) .+ 1200 .@ Hat :< (Cash, Yen))
-- | Express dollars in yen at 150 yen per dollar, preserving account and side.
toYen :: MoneyDecimal
      -> HatBase (AccountTitles, Unit)
      -> (MoneyDecimal, HatBase (AccountTitles, Unit))
toYen amount (direction :< (account, Dollar)) = (amount * 150, direction :< (account, Yen))
toYen amount basis = (amount, basis)

-- | Reporting representation at the January 31 rate, equal to the exchange rate.
yenJournal :: Book
yenJournal = Journal.map (Algebra.mapPosting toYen) sourceJournal

-- | Check the converted journal without changing its notes or term sequences.
acceptedJanuary :: Either String (Admission.Admitted EntryNote (HatBase (AccountTitles, Unit)))
acceptedJanuary = either (Left . show . Admission.failureErrors) Right
    (Admission.admit yenJournal)
-- | Print a labeled result, retaining the library's diagnostic constructors.
printNamed :: Show a => String -> a -> IO ()
printNamed label value = putStrLn (label ++ ": " ++ show value)

-- | Stop the example on an unexpected checked failure.
require :: Show e => Either e a -> IO a
require = either (ioError . userError . show) pure

-- | Drop the currency element only after checking every term is in yen.
-- This reporting projection removes the currency element; it does not net terms.
auditLedger :: Entry -> Either String (Alg MoneyDecimal (HatBase AccountTitles))
auditLedger ledger
    | Algebra.foldEntries allYen True ledger = Right (Algebra.mapPosting dropUnit ledger)
    | otherwise = Left "Audit requires yen on every term"
  where
    allYen :: Bool -> MoneyDecimal -> HatBase (AccountTitles, Unit) -> Bool
    allYen result _ (_ :< (_, unit)) = result && unit == Yen

    dropUnit :: MoneyDecimal
             -> HatBase (AccountTitles, Unit)
             -> (MoneyDecimal, HatBase AccountTitles)
    dropUnit amount (direction :< (account, _)) = (amount, direction :< account)
-- | January 31: defer February's half of the rent, using the rent transfer table.
rentAdjustment :: Entry -> Either String Entry
rentAdjustment ledger = do
    table <- either (Left . show) Right $ mkTransferTable
        [(RentExpense, (.#)) .-> (PrepaidExpenses, (.#)) |% Portion 1 2]
    either (Left . show) Right (transferEntries table ledger)

-- | Keep the currency element when building the periodic inventory adjustment.
yenBase :: Entries.MkBase (HatBase (AccountTitles, Unit))
yenBase direction account = direction :< (account, Yen)

-- | No beginning inventory; the January 31 physical count is worth 200 yen at cost.
inventoryAdjustment :: Entry
inventoryAdjustment = Entries.cogsAdjustmentEntries yenBase 0 200

-- | Add adjustments under distinct notes and check the resulting journal again.
adjustedJanuary :: Book -> Either String Book
adjustedJanuary journal = do
    rent <- rentAdjustment (Journal.toAlg journal)
    let adjusted :: Book
        adjusted = journal
                .+ record 31 "Defer February rent" rent
                .+ record 31 "Ending inventory" inventoryAdjustment
    admitted <- either (Left . show . Admission.failureErrors) Right (Admission.admit adjusted)
    pure (Admission.admittedJournal admitted)
-- | Generate additional closing entries from the adjusted ledger, then check the resulting journal.
closedJanuary :: Book -> Either String Book
closedJanuary journal = do
    additions <- either (Left . show) Right (Closing.closingEntries (Journal.toAlg journal))
    let closed :: Book
        closed = journal .+ record 31 "Close January" additions
    admitted <- either (Left . show . Admission.failureErrors) Right (Admission.admit closed)
    pure (Admission.admittedJournal admitted)
-- | Print the balance-sheet lines and totals for this example.
printBalanceSheet :: Statements.FinancialStatements MoneyDecimal -> IO ()
printBalanceSheet statements = do
    let lines' = Statements._statementLines statements
        inSections sections =
            [ line | section <- sections
                   , line <- lines'
                   , Statements._lineSection line == section
            ]
        assets = inSections [Statements.CurrentAssetsSection, Statements.NoncurrentAssetsSection]
        liabilitiesAndEquity = inSections
            [ Statements.CurrentLiabilitiesSection
            , Statements.NoncurrentLiabilitiesSection
            , Statements.EquitySection
            ]
    mapM_ printLine assets
    printNamed "Total assets" (sum (map Statements._lineAmount assets))
    mapM_ printLine liabilitiesAndEquity
    printNamed "Total liabilities and equity"
        (sum (map Statements._lineAmount liabilitiesAndEquity))

-- | Keep the displayed section, account label, side, and magnitude visible.
printLine :: Statements.StatementLine MoneyDecimal -> IO ()
printLine line = putStrLn $ unwords
    [ show (Statements._lineSection line)
    , show (Statements._lineLabel line)
    , show (Statements._lineSide line)
    , showValue (Statements._lineAmount line)
    ]

In the parent’s books, debit subsidiary shares and credit deposits for 3,000 yen. In the parent’s standalone balance sheet, SubsidiaryStocks represents subsidiary shares carried at acquisition cost, with no equity-method adjustment. In the subsidiary’s books, debit cash and credit capital stock for 3,000 yen. Use bar to obtain the parent’s February 1 balances, then identify each entity’s balances with a TrialBalanceSource.

-- | Parent and subsidiary trial balances immediately after the February 1 contribution.
entityBalances :: Alg MoneyDecimal (HatBase AccountTitles)
               -> NonEmpty (Consolidation.TrialBalanceSource String MoneyDecimal)
entityBalances januaryEnd =
    Consolidation.TrialBalanceSource "shop" parent :|
    [Consolidation.TrialBalanceSource "subsidiary" subsidiary]
  where
    parent = bar (januaryEnd
        .+ (3000 .@ Not :< SubsidiaryStocks)
        .+ (3000 .@ Hat :< Deposits))
    subsidiary = (3000 .@ Not :< Cash)
               .+ (3000 .@ Not :< CapitalStock)

Eliminate the investment and subsidiary capital

The parent’s subsidiary shares and the subsidiary’s capital stock record the same contribution within the group. Eliminate them with a debit to CapitalStock and a credit to SubsidiaryStocks, each for 3,000 yen. Both terms decrease a balance, so both use Hat. Record the entry as a WorksheetAdjustment linked to both companies. The adjustment belongs to the consolidated worksheet.

-- | Debit the subsidiary's capital and credit the parent's investment.
elimination :: Consolidation.WorksheetAdjustment String String MoneyDecimal
elimination = Consolidation.WorksheetAdjustment
    "investment against subsidiary capital"
    ("shop" :| ["subsidiary"])
    ((3000 .@ Hat :< CapitalStock)
  .+ (3000 .@ Hat :< SubsidiaryStocks))

Supply the period result, its attribution, and the equity roll-forwards in a WorksheetLinkage. February’s result is zero at incorporation. January’s 1,100 yen is February’s opening retained earnings. With zero dividends and a zero February result, the closing figure used in the roll-forward and the balance-sheet figure are also 1,100 yen at the reporting date. The parent owns all the shares, so the noncontrolling-interest fields have zero amounts or NoBalance.

validateConsolidationWorksheet checks the balance of each source and adjustment, the adjustment’s source IDs and permitted accounts, and the equations among the supplied linkage figures. Cross-check those figures against the statement balances separately. The example takes retained earnings from the January ledger and checks the consolidated balances after combining.

-- | Link February's opening and reporting balances at the formation date.
linkage :: TrialBalance.AccountBalance MoneyDecimal -> Consolidation.WorksheetLinkage MoneyDecimal
linkage retained = Consolidation.WorksheetLinkage
    { Consolidation._profitOrLossNetIncome = Statements.PeriodBreakEven
    , Consolidation._profitOrLossNetIncomeAttributableToOwners = Statements.PeriodBreakEven
    , Consolidation._statementOfChangesNetIncomeAttributableToOwners = Statements.PeriodBreakEven
    , Consolidation._openingRetainedEarnings = retained
    , Consolidation._retainedEarningsDividends = 0
    , Consolidation._statementOfChangesClosingRetainedEarnings = retained
    , Consolidation._balanceSheetRetainedEarnings = retained
    , Consolidation._openingNonControllingInterests = TrialBalance.NoBalance
    , Consolidation._nonControllingInterestsPeriodShare = Statements.PeriodBreakEven
    , Consolidation._nonControllingInterestsDividends = 0
    , Consolidation._statementOfChangesClosingNonControllingInterests = TrialBalance.NoBalance
    , Consolidation._balanceSheetNonControllingInterests = TrialBalance.NoBalance
    }

Inspect the consolidated balance sheet

combinedWorksheet adds the two trial balances and the elimination with .+, retaining terms on the same base. Apply bar explicitly to inspect the net totals, and present the combined ledger as a Combined balance sheet.

main :: IO ()
main = do
    accepted <- require acceptedJanuary
    adjusted <- require (adjustedJanuary (Admission.admittedJournal accepted))
    closed <- require (closedJanuary adjusted)
    januaryEnd <- require (auditLedger (Journal.toAlg closed))
    let retained = TrialBalance.balanceFor RetainedEarnings
            (TrialBalance.accountBalances januaryEnd)
        input = Consolidation.WorksheetInput
            (entityBalances januaryEnd) [elimination] (linkage retained)
    worksheet <- require (Consolidation.validateConsolidationWorksheet input)
    let combined = Consolidation.combinedWorksheet worksheet
        net = bar combined
        context = (Statements.jcciSecondGradeContext Statements.Combined)
            { Statements._presentationProfile = Statements.CanonicalEnglish }
        balances = TrialBalance.accountBalances net
    unless (TrialBalance.balanceFor RetainedEarnings balances == retained) $
        ioError (userError "Combined retained earnings do not match the worksheet linkage")
    printNamed "Combined net totals (debit, credit)" (norm (decL net), norm (decR net))
    printNamed "Investment balance" (TrialBalance.balanceFor SubsidiaryStocks balances)
    printNamed "Group capital stock" (TrialBalance.balanceFor CapitalStock balances)
    statement <- require (Statements.present context TrialBalance.AfterClosing combined)
    putStrLn "\nOpening consolidated balance sheet at February 1 (yen)"
    printBalanceSheet statement

In your project directory, run stack exec -- ghc -Wall -Werror Main.hs -o consolidation-example, then run ./consolidation-example.

Combined net totals (debit, credit): (11100,11100)
Investment balance: NoBalance
Group capital stock: CreditBalance 10000

Opening consolidated balance sheet at February 1 (yen)
CurrentAssetsSection "Cash" Debit 8300
CurrentAssetsSection "Savings deposits" Debit 2000
CurrentAssetsSection "Merchandise inventory" Debit 200
CurrentAssetsSection "Prepaid expenses" Debit 600
Total assets: 11100
EquitySection "Capital stock" Credit 10000
EquitySection "Retained earnings" Credit 1100
Total liabilities and equity: 11100

The investment has no remaining balance. Capital stock is 10,000 yen, the parent’s own capital. The group shows cash of 8,300 yen and deposits of 2,000 yen. Together with inventory of 200 yen and prepaid expenses of 600 yen, assets total 11,100 yen. There are no liabilities, and equity totals 11,100 yen.

Tested with exchangealgebra-0.6.1.1 on 2026-11-20.

Reference

Type or operationInputs and result
TrialBalanceSourceIdentify one entity and supply its balanced trial balance over HatBase AccountTitles.
WorksheetAdjustmentSupply an independently balanced adjustment with its own ID and the nonempty list of source IDs it affects.
WorksheetLinkageSupply the period result and its attribution, and reconcile opening balances, period movements, dividends, and closing balances for retained earnings and noncontrolling interests.
validateConsolidationWorksheet inputValidate the worksheet or return a nonempty list of WorksheetError values identifying the rejected inputs.
combinedWorksheet, validatedSources, and validatedAdjustmentsProject the combined ledger, or retrieve the original source and adjustment columns to trace each contribution.

Reading journals from CSV

Import the shop’s January 28 cash sale and January 30 rent payment from CSV. Both transactions are in yen, so the input uses HatBase AccountTitles with the currency fixed for the file. The accepted journal retains a separate note for each transaction.

Use exchangealgebra-0.6.1.1 in the project prepared in Add the package to a Stack project. Save the Haskell blocks in their displayed order as Main.hs.

Write one CSV row per term

Save the CSV as january-import.csv in the same directory as Main.hs. The header gives the journal side, account title, amount, and optional note. Use debit or credit for the side and an unsigned decimal amount without thousands separators. Use the same nonempty note for every term in one transaction and a distinct note for each other transaction. The parser trims spaces around fields and skips blank lines and comment lines starting with # after whitespace. Commas always separate fields, so keep commas out of the notes.

side,account,amount,note
debit,Cash,2000,Jan 28 Cash sale
credit,Sales,2000,Jan 28 Cash sale
debit,RentExpense,1200,Jan 30 January and February rent
credit,Cash,1200,Jan 30 January and February rent

For each line, the CSV parser resolves the account with parseAccountTitle. It accepts canonical English names and registered aliases. normalizeTitle lowercases the text, removes punctuation, and collapses whitespace before lookup. For example, A/R normalizes to ar and resolves to AccountsReceivable.

See Account titles and their attributes for the sources of the registered aliases.

{-# LANGUAGE OverloadedStrings #-}

module Main where

import Data.List (groupBy, sortOn)
import Data.String (IsString, fromString)
import ExchangeAlgebra (AccountTitles(..), Alg, HatBase, MoneyDecimal, Side(..), decL, decR, norm)
import qualified ExchangeAlgebra.IO.Input as Input
import qualified ExchangeAlgebra.IO.Input.Admission as Admission
import qualified ExchangeAlgebra.IO.Input.Csv as Csv
import qualified ExchangeAlgebra.Journal as Journal

Code carried over from earlier chapters

-- | Stop the example on an unexpected checked failure.
require :: Show e => Either e a -> IO a
require = either (ioError . userError . show) pure

Check the imported journal

parseJournalCsv returns one algebra value with all the parsed terms. Its debit and credit totals describe the file as a whole. To check transactions individually, use parseNotedJournalCsv to retain the note column. Group the rows by note and pass one group per transaction to checkedJournal. It checks each group’s accounts, term amounts, and debit and credit totals before constructing the journal.

-- | Group the parsed terms by transaction key, keeping the order within each entry.
groupTransactions :: Ord note
                  => [(Side, AccountTitles, MoneyDecimal, note)]
                  -> [(note, [(Side, AccountTitles, MoneyDecimal)])]
groupTransactions rows =
    [ (note, map withoutNote entry)
    | entry@((_, _, _, note) : _) <- groupBy sameNote (sortOn noteOf rows)
    ]
  where
    noteOf (_, _, _, note) = note
    sameNote left right = noteOf left == noteOf right
    withoutNote (side, account, amount, _) = (side, account, amount)

-- | Require a transaction key on every CSV term before grouping by note.
checkNotes :: (Eq note, IsString note)
           => [(Side, AccountTitles, MoneyDecimal, note)] -> Either String ()
checkNotes rows
    | any (\(_, _, _, note) -> note == "") rows = Left "Missing transaction key in note"
    | otherwise = Right ()

Compare the checked journal with the amounts from the sale and rent records using reconcileSources. It reports absent or unexpected transaction keys and compares the expected amount for each key with its debit total. Pass the journal to admit to obtain the Admitted value described in Checking a journal.

main :: IO ()
main = do
    input <- fromString <$> readFile "january-import.csv"
    flat <- require (Csv.parseJournalCsv input :: Either Input.ConvError
        (Alg MoneyDecimal (HatBase AccountTitles)))
    putStrLn $ "Parsed term totals (debit, credit): "
            ++ show (norm (decL flat), norm (decR flat))

    rows <- require (Csv.parseNotedJournalCsv Csv.scientificAmount input)
    require (checkNotes rows)
    journal <- require (Input.checkedJournal (groupTransactions rows))
    let sources = [("Jan 28 Cash sale", 2000), ("Jan 30 January and February rent", 1200)]
        differences = Input.reconcileSources sources journal
    case differences of
        [] -> pure ()
        _ -> ioError (userError (show differences))
    accepted <- require (Admission.admit journal)
    let ledger = Journal.toAlg (Admission.admittedJournal accepted)
    putStrLn $ "Source differences: " ++ show differences
    putStrLn $ "Admitted journal totals (debit, credit): "
            ++ show (norm (decL ledger), norm (decR ledger))
    printDiagnostics

Diagnose an unknown title and an unbalanced entry

If the sale credit is spelled Saels, the CSV parser returns UnknownAccount. For sources already represented as text triples, certifyJournalText can report a balanced transaction with an unresolved name as BalancedUnresolved. Correct the name before submitting the journal for checking. If the sale credit is 1,900 yen against a 2,000-yen debit, checkedJournal reports Imbalanced under the sale’s transaction key.

-- | Show the results of a misspelled title and a separate amount error.
printDiagnostics :: IO ()
printDiagnostics = do
    putStrLn $ "Normalized title: " ++ show (Input.normalizeTitle "  A/R  ")
    putStrLn $ "Account name: " ++ show (Input.parseAccountTitle "  A/R  ")
    let typoCsv = "side,account,amount\ndebit,Cash,2000\ncredit,Saels,2000\n"
    putStrLn $ "CSV title error: "
        ++ show (Csv.parseJournalCsv typoCsv :: Either Input.ConvError
            (Alg MoneyDecimal (HatBase AccountTitles)))
    let unresolved = Input.certifyJournalText
            [("Jan 28 Cash sale" :: String, [("debit", "Cash", 2000 :: MoneyDecimal),
                                            ("credit", "Saels", 2000)])]
    putStrLn $ "Text certification: " ++ show unresolved
    let unbalanced = Input.checkedJournal
            [("Jan 28 Cash sale" :: String, [(Debit, Cash, 2000 :: MoneyDecimal),
                                            (Credit, Sales, 1900)])]
    putStrLn $ "Entry balance error: " ++ show unbalanced

In your project directory, run stack exec -- ghc -Wall -Werror Main.hs -o input-example, then run ./input-example.

Parsed term totals (debit, credit): (3200,3200)
Source differences: []
Admitted journal totals (debit, credit): (3200,3200)
Normalized title: "ar"
Account name: Right AccountsReceivable
CSV title error: Left (UnknownAccount "Saels")
Text certification: BalancedUnresolved {_certResolved = [("Jan 28 Cash sale",[(Debit,Cash,2000)])], _certUnresolved = [("Jan 28 Cash sale",[(1,"Saels",UnknownAccount "Saels")])], _certDebitTotal = 2000, _certCreditTotal = 2000}
Entry balance error: Left (EntryErrors "Jan 28 Cash sale" (Imbalanced {_debitTotal = 2000, _creditTotal = 1900} :| []) :| [])

The checked journal’s debit and credit totals are both 3,200 yen, and the source comparison returns an empty list. The name and amount errors come from the separate diagnostic examples.

Tested with exchangealgebra-0.6.1.1 on 2026-11-20.

Reference

Type or operationInputs and result
parseJournalCsv and parseNotedJournalCsvParse fixed-schema CSV. The former returns one algebra value. The latter takes an amount parser such as scientificAmount and returns individual rows with notes.
normalizeTitle and parseAccountTitleNormalize names for lookup and resolve them to account titles. A name with several matches returns AmbiguousAccount and its candidates.
checkedJournalBuild an ordinary journal from keyed entries with resolved titles. Duplicate keys and invalid entries produce journal errors.
certifyJournalTextCertify entries supplied as side text, account text, and amount. The result is FullyResolved, BalancedUnresolved, or Rejected.
reconcileSourcesCompare the transaction identifiers and amounts supplied by the reconciliation source with the journal.
admitCheck the journal at the note level and return an Admitted value on success.

Writing books and statements

The shop’s checked January journal contains the terms for its books. Its pre-adjustment, adjusted, and closed versions supply the figures for the trial balances, the worksheet, and the financial statements. Use the row builders in ExchangeAlgebra.IO.Output.Statements to obtain text cells for each report.

Use exchangealgebra-0.6.1.1 in the project prepared in Add the package to a Stack project. Save the Haskell blocks in their displayed order as Main.hs.

Lay out the journal and general ledger by date

Reuse the yen conversion, journal checking, adjustments, closing entries, and reporting context from Financial statements. For the dated reports, select the original January entries by the date in their notes. Check the amounts are in yen before replacing the currency element with the date.

Code carried over from earlier chapters

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}

module Main where

import Text.Printf (printf)
import Text.Read (readMaybe)

import ExchangeAlgebra hiding (Yen, Dollar, map)
import qualified ExchangeAlgebra.Algebra.Core as Algebra
import ExchangeAlgebra.Journal ((.|))
import qualified ExchangeAlgebra.Journal as Journal
import qualified ExchangeAlgebra.IO.Input.Admission as Admission
import qualified ExchangeAlgebra.Accounting.Entries as Entries
import qualified ExchangeAlgebra.Accounting.Closing as Closing

import qualified ExchangeAlgebra.Accounting.TrialBalance as TrialBalance
import qualified ExchangeAlgebra.Accounting.Statements as Statements
import qualified ExchangeAlgebra.IO.Output.Statements as Output

-- | Currency element retained in the source journal.
data Unit
    = Yen       -- ^ Japanese yen.
    | Dollar    -- ^ US dollars.
    | Unit      -- ^ Inapplicable in an entry; unrestricted in a query.
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Element Unit where
    wildcard = Unit

instance ExBaseClass (HatBase (AccountTitles, Unit)) where
    getAccountTitle (_ :< (account, _)) = account
    setAccountTitle (direction :< (_, unit)) account = direction :< (account, unit)

-- | Date and description; the example supplies valid calendar dates.
data EntryNote = EntryNote (Integer, Int, Int) String
    deriving (Eq, Ord, Show, Generic, Hashable)

instance Journal.Note EntryNote where
    plank = EntryNote (0, 0, 0) ""

-- | One entry with account and currency elements; the alias adds no validation.
type Entry = Alg MoneyDecimal (HatBase (AccountTitles, Unit))

-- | January journal with one distinct note per transaction.
type Book = Journal.Journal EntryNote MoneyDecimal (HatBase (AccountTitles, Unit))
-- | Attach a January date and description after constructing all terms.
record :: Int -> String -> Entry -> Book
record day description algebra = algebra .| EntryNote (2026, 1, day) description

-- | January 1: capital paid into Bank A's savings account.
opening :: Book
opening = record 1 "Opening capital"
    (10000 .@ Not :< (Deposits, Yen)
  .+ 10000 .@ Not :< (CapitalStock, Yen))

-- | Transactions through January 30, before adjusting entries.
sourceJournal :: Book
sourceJournal = opening
    .+ record 10 "Withdrawal from Bank A"
        (3000 .@ Not :< (Cash, Yen) .+ 3000 .@ Hat :< (Deposits, Yen))
    .+ record 15 "Withdrawal from Bank A"
        (2000 .@ Not :< (Cash, Yen) .+ 2000 .@ Hat :< (Deposits, Yen))
    .+ record 20 "Purchase of goods"
        (500 .@ Not :< (Purchases, Yen) .+ 500 .@ Hat :< (Cash, Yen))
    .+ record 25 "Yen-dollar exchange"
        (1500 .@ Hat :< (Cash, Yen) .+ 10 .@ Not :< (Cash, Dollar))
    .+ record 28 "Cash sale"
        (2000 .@ Not :< (Cash, Yen) .+ 2000 .@ Not :< (Sales, Yen))
    .+ record 30 "January and February rent"
        (1200 .@ Not :< (RentExpense, Yen) .+ 1200 .@ Hat :< (Cash, Yen))
-- | Express dollars in yen at 150 yen per dollar, preserving account and side.
toYen :: MoneyDecimal
      -> HatBase (AccountTitles, Unit)
      -> (MoneyDecimal, HatBase (AccountTitles, Unit))
toYen amount (direction :< (account, Dollar)) = (amount * 150, direction :< (account, Yen))
toYen amount basis = (amount, basis)

-- | Reporting representation at the January 31 rate, equal to the exchange rate.
yenJournal :: Book
yenJournal = Journal.map (Algebra.mapPosting toYen) sourceJournal

-- | Check the converted journal without changing its notes or term sequences.
acceptedJanuary :: Either String (Admission.Admitted EntryNote (HatBase (AccountTitles, Unit)))
acceptedJanuary = either (Left . show . Admission.failureErrors) Right
    (Admission.admit yenJournal)
-- | Print a labeled result, retaining the library's diagnostic constructors.
printNamed :: Show a => String -> a -> IO ()
printNamed label value = putStrLn (label ++ ": " ++ show value)

-- | Stop the example on an unexpected checked failure.
require :: Show e => Either e a -> IO a
require = either (ioError . userError . show) pure

-- | Drop the currency element only after checking every term is in yen.
-- This reporting projection removes the currency element; it does not net terms.
auditLedger :: Entry -> Either String (Alg MoneyDecimal (HatBase AccountTitles))
auditLedger ledger
    | Algebra.foldEntries allYen True ledger = Right (Algebra.mapPosting dropUnit ledger)
    | otherwise = Left "Audit requires yen on every term"
  where
    allYen :: Bool -> MoneyDecimal -> HatBase (AccountTitles, Unit) -> Bool
    allYen result _ (_ :< (_, unit)) = result && unit == Yen

    dropUnit :: MoneyDecimal
             -> HatBase (AccountTitles, Unit)
             -> (MoneyDecimal, HatBase AccountTitles)
    dropUnit amount (direction :< (account, _)) = (amount, direction :< account)
-- | January 31: defer February's half of the rent, using the rent transfer table.
rentAdjustment :: Entry -> Either String Entry
rentAdjustment ledger = do
    table <- either (Left . show) Right $ mkTransferTable
        [(RentExpense, (.#)) .-> (PrepaidExpenses, (.#)) |% Portion 1 2]
    either (Left . show) Right (transferEntries table ledger)

-- | Keep the currency element when building the periodic inventory adjustment.
yenBase :: Entries.MkBase (HatBase (AccountTitles, Unit))
yenBase direction account = direction :< (account, Yen)

-- | No beginning inventory; the January 31 physical count is worth 200 yen at cost.
inventoryAdjustment :: Entry
inventoryAdjustment = Entries.cogsAdjustmentEntries yenBase 0 200

-- | Add adjustments under distinct notes and check the resulting journal again.
adjustedJanuary :: Book -> Either String Book
adjustedJanuary journal = do
    rent <- rentAdjustment (Journal.toAlg journal)
    let adjusted :: Book
        adjusted = journal
                .+ record 31 "Defer February rent" rent
                .+ record 31 "Ending inventory" inventoryAdjustment
    admitted <- either (Left . show . Admission.failureErrors) Right (Admission.admit adjusted)
    pure (Admission.admittedJournal admitted)
-- | Generate additional closing entries from the adjusted ledger, then check the resulting journal.
closedJanuary :: Book -> Either String Book
closedJanuary journal = do
    additions <- either (Left . show) Right (Closing.closingEntries (Journal.toAlg journal))
    let closed :: Book
        closed = journal .+ record 31 "Close January" additions
    admitted <- either (Left . show . Admission.failureErrors) Right (Admission.admit closed)
    pure (Admission.admittedJournal admitted)
-- | Choose English labels for the shop's standalone statements.
context :: Statements.ReportingContext MoneyDecimal
context = (Statements.jcciSecondGradeContext Statements.Standalone)
    { Statements._presentationProfile = Statements.CanonicalEnglish }

-- | Present the adjusted Purchases balance under the cost-of-sales title.
incomeContext :: Statements.ReportingContext MoneyDecimal
incomeContext = context
    { Statements._presentationRelabels =
        [Statements.PresentationRelabel Purchases SalesCost "Periodic inventory adjustment"]
    }

Pass the dated terms and a function that extracts the date to journalRows and accountLedgerRows. The journal places each day’s debit and credit terms in columns. The general ledger groups terms by account and orders each side by date. Request Cash to inspect the cash account. Both reports retain the individual terms.

-- | Select one date while retaining the terms from every matching note.
onJanuaryDay :: Int -> Book -> Entry
onJanuaryDay day = Journal.toAlg . Journal.filterWithNote matches
  where
    matches (EntryNote date _) _ = date == (2026, 1, day)

-- | Put the note's date on each term in the day selected for the dated reports.
printDatedBooks :: Book -> IO ()
printDatedBooks journal = do
    dated <- traverse datedPostings [1 .. 30]
    let postings = foldr (.+) mempty dated
        postingDay (_ :< (_, day)) = day
    putStrLn "Journal by day"
    mapM_ print (Output.journalRows postings postingDay)
    putStrLn "\nGeneral ledger (Cash)"
    mapM_ print (Output.accountLedgerRows [Cash] postings postingDay)
  where
    datedPostings day = do
        let date = printf "2026-01-%02d" day
        calendarDay <- require $ maybe (Left ("Invalid date " ++ date)) Right (readMaybe date)
        ledger <- require (auditLedger (onJanuaryDay day journal))
        pure $ Algebra.mapPosting
            (\amount (direction :< account) -> (amount, direction :< (account, calendarDay)))
            ledger

Lay out the trial balances and worksheet

Give compoundTrialBalanceRows the pre-adjustment ledger to display a trial balance with debit and credit totals and net balances by account. Give worksheetRows the same ledger and the separate rent and inventory adjustments dated January 31. The eight-column worksheet shows debit and credit pairs for the pre-adjustment trial balance (balances only), adjustments, profit and loss, and balance sheet.

Pass the ledger with closing entries to postClosingTrialBalanceRows to display the post-closing trial balance. This report selects the asset, liability, and equity accounts. The trial balance and worksheet row builders compute their totals and net balances internally as reporting projections.

-- | Use the January 31 adjusting entries separately from the pre-adjustment ledger.
printTrialAndWorksheet :: Book -> Book -> Book -> IO ()
printTrialAndWorksheet original adjusted closed = do
    beforeAdjusting <- require (auditLedger (Journal.toAlg original))
    adjustments <- require (auditLedger (onJanuaryDay 31 adjusted))
    afterClosing <- require (auditLedger (Journal.toAlg closed))
    putStrLn "\nPre-adjustment compound trial balance"
    mapM_ print (Output.compoundTrialBalanceRows beforeAdjusting)
    putStrLn "\nEight-column worksheet"
    mapM_ print (Output.worksheetRows beforeAdjusting adjustments)
    putStrLn "\nPost-closing trial balance"
    mapM_ print (Output.postClosingTrialBalanceRows afterClosing)

Select financial statement rows

Present balances after adjustments and before closing entries for the income statement. Use the ledger with closing entries for the balance sheet. Pass the revenue and expense sections to financialStatementRows for the income statement, and the asset, liability, and equity sections for the balance sheet. The row column distinguishes line from subtotal. Sum account lines and use the subtotals as separate results to avoid counting the same amounts twice.

-- | Select the financial statement sections appropriate to each stage.
printStatementRows :: Book -> Book -> IO ()
printStatementRows adjusted closed = do
    beforeClosing <- require (auditLedger (Journal.toAlg adjusted))
    afterClosing <- require (auditLedger (Journal.toAlg closed))
    income <- require (Statements.present incomeContext TrialBalance.BeforeClosing beforeClosing)
    position <- require (Statements.present context TrialBalance.AfterClosing afterClosing)
    incomeRows <- require $ Output.financialStatementRows
        [Statements.RevenueSection, Statements.ExpenseSection] income
    balanceRows <- require $ Output.financialStatementRows
        [ Statements.CurrentAssetsSection
        , Statements.NoncurrentAssetsSection
        , Statements.CurrentLiabilitiesSection
        , Statements.NoncurrentLiabilitiesSection
        , Statements.EquitySection
        ] position
    putStrLn "\nIncome statement for January"
    mapM_ print incomeRows
    putStrLn "\nBalance sheet at January 31"
    mapM_ print balanceRows

Inspect the text rows

The program prints each report as lists of text cells on standard output. The file writers in Reference serialize rows as CSV.

main :: IO ()
main = do
    accepted <- require acceptedJanuary
    let original = Admission.admittedJournal accepted
    adjusted <- require (adjustedJanuary original)
    closed <- require (closedJanuary adjusted)
    putStrLn "January reports (yen)"
    printDatedBooks original
    printTrialAndWorksheet original adjusted closed
    printStatementRows adjusted closed

In your project directory, run stack exec -- ghc -Wall -Werror Main.hs -o output-example, then run ./output-example.

January reports (yen)
Journal by day
["Day","Debit","Amount","Credit","Amount"]
["2026-01-01","Deposits","10000","CapitalStock","10000"]
["2026-01-10","Cash","3000","Deposits","3000"]
["2026-01-15","Cash","2000","Deposits","2000"]
["2026-01-20","Purchases","500","Cash","500"]
["2026-01-25","Cash","1500","Cash","1500"]
["2026-01-28","Cash","2000","Sales","2000"]
["2026-01-30","RentExpense","1200","Cash","1200"]

General ledger (Cash)
["Cash","","",""]
["Date","Debit","Date","Credit"]
["2026-01-10","3000","2026-01-20","500"]
["2026-01-15","2000","2026-01-25","1500"]
["2026-01-25","1500","2026-01-30","1200"]
["2026-01-28","2000","",""]

Pre-adjustment compound trial balance
["Debit Balance","Debit Total","Account Title","Credit Total","Credit Balance"]
["5300","8500","Cash","3200",""]
["5000","10000","Deposits","5000",""]
["","0","CapitalStock","10000","10000"]
["1200","1200","RentExpense","0",""]
["500","500","Purchases","0",""]
["","0","Sales","2000","2000"]
["12000","20200","Total","20200","12000"]

Eight-column worksheet
["Account Title","Trial Balance","","Adjustments","","Profit & Loss","","Balance Sheet",""]
["","Debit","Credit","Debit","Credit","Debit","Credit","Debit","Credit"]
["Cash","5300","","","","","","5300",""]
["Deposits","5000","","","","","","5000",""]
["CapitalStock","","10000","","","","","","10000"]
["RentExpense","1200","","","600","600","","",""]
["Purchases","500","","","200","300","","",""]
["Sales","","2000","","","","2000","",""]
["MerchandiseInventory","","","200","","","","200",""]
["PrepaidExpenses","","","600","","","","600",""]
["Subtotal","12000","12000","","","900","2000","11100","10000"]
["Net Income","","","","","1100","","","1100"]
["Total","","","","","2000","2000","11100","11100"]

Post-closing trial balance
["Debit","Account Title","Credit"]
["5300","Cash",""]
["5000","Deposits",""]
["","CapitalStock","10000"]
["","RetainedEarnings","1100"]
["200","MerchandiseInventory",""]
["600","PrepaidExpenses",""]
["11100","Total","11100"]

Income statement for January
["section","account","label","row","side","amount"]
["RevenueSection","Sales","Sales","line","Credit","2000"]
["ExpenseSection","SalesCost","Cost of sales","line","Debit","300"]
["ExpenseSection","RentExpense","Rent","line","Debit","600"]
["","","Net income","subtotal","Credit","1100"]

Balance sheet at January 31
["section","account","label","row","side","amount"]
["CurrentAssetsSection","Cash","Cash","line","Debit","5300"]
["CurrentAssetsSection","Deposits","Savings deposits","line","Debit","5000"]
["CurrentAssetsSection","MerchandiseInventory","Merchandise inventory","line","Debit","200"]
["CurrentAssetsSection","PrepaidExpenses","Prepaid expenses","line","Debit","600"]
["EquitySection","CapitalStock","Capital stock","line","Credit","10000"]
["EquitySection","RetainedEarnings","Retained earnings","line","Credit","1100"]

The cash ledger shows the 2,000-yen sale as a debit on January 28. The worksheet shows net income of 1,100 yen, which appears as a subtotal in the income statement. In the post-closing trial balance, the carried balances total 11,100 yen on each side.

Tested with exchangealgebra-0.6.1.1 on 2026-11-20.

Reference

Type or operationInputs and result
journalRows and writeJournalLay out a journal by day from terms and a date accessor. The writer saves the rows to a path.
accountLedgerRows and writeAccountOfLay out a general ledger for the requested accounts from dated terms.
compoundTrialBalanceRows and writeCompoundTrialBalanceLay out debit and credit totals and net balances from one ledger.
worksheetRows and writeWorksheetLay out the eight-column worksheet from a pre-adjustment ledger and separate adjusting entries.
postClosingTrialBalanceRows and writePostClosingTrialBalanceLay out the balances carried forward from a closed ledger.
financialStatementRows and writeFinancialStatementsRender the requested sections of FinancialStatements. A request for revenue or expenses without a period-result subtotal returns PeriodResultMissing.
ExchangeAlgebra.IO.Output.Csv.writeCSVWrite a table of text cells to a file. Every cell is quoted, and embedded quotation marks are doubled.