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
- Consult Definitions and axioms for the formal rules for matching elements, adding terms, and separating debits from credits, or go straight to Installation and modules to start using the library.
Getting started
- In Installation and modules, add the package to a Stack project and select imports by layer.
- In Record a withdrawal, write a journal entry in exchange algebra and check that the debit and credit totals agree.
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
- In Account titles and their attributes, look up how the library classifies an account title.
- In Built-in account titles, find an account title to use in an entry.
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
- In Reading journals from CSV, import term rows and diagnose an unknown account title and an unbalanced entry.
- In Writing books and statements, produce CSV rows for the journal, general ledger, trial balances, worksheet, and financial statements.
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. | Transaction | Debit | Amount | Credit | Amount |
|---|---|---|---|---|---|
| 1 | The owner invests cash. | Cash | 1,000 | Capital stock | 1,000 |
| 2 | The shop buys goods for cash. | Purchases | 600 | Cash | 600 |
| 3 | The shop sells goods on credit. | Accounts receivable | 900 | Sales | 900 |
| 4 | The shop collects part of the receivable. | Cash | 500 | Accounts receivable | 500 |
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.
| Operation | Effect |
|---|---|
| Hat | Swap the two sequences at each base, preserving every amount. |
| Bar | Total each sequence at each base and cancel the two totals. Keep the excess on the larger side and drop a zero remainder. |
| Sum | Concatenate the corresponding sequences. |
| Scalar multiplication | Multiply every amount by the same nonnegative scalar. |
| Norm | Sum 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.
-
Hat is an involution. Applying hat twice restores the original terms.
$$ \widehat{\widehat{f_i}}(e_i) = f_i(e_i). $$
-
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. $$
-
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. $$
-
Norm homogeneity. Scaling the terms scales their total.
$$ \operatorname{norm}(a \ast x) = a \cdot \operatorname{norm}(x), \qquad a \ge 0. $$
-
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.
| Division | Not | Hat |
|---|---|---|
| Assets | Increase (debit) | Decrease (credit) |
| Liabilities, equity | Increase (credit) | Decrease (debit) |
| Revenue | Recognition (credit) | Reversal (debit) |
| Expenses | Recognition (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.
| Layer | Modules to import | Purpose |
|---|---|---|
| Algebra | ExchangeAlgebra.Algebra | Elements, bases, the Alg type, and redundant-algebra operations. |
| Algebra | ExchangeAlgebra.Algebra.Element, .Base, .Core, .Value | Individual parts of the algebra; these abbreviated names share the prefix ExchangeAlgebra.Algebra. |
| Algebra | ExchangeAlgebra.Algebra.Posting, ExchangeAlgebra.Algebra.Transfer | Checked term construction and generic transformations of bases. |
| Journal | ExchangeAlgebra.Journal, ExchangeAlgebra.Journal.Transfer | Terms indexed by notes, and transformations of those journals. Qualify function names shared with Algebra and import the operator .| unqualified. |
| Accounting | ExchangeAlgebra.Accounting, ExchangeAlgebra.Accounting.Account, ExchangeAlgebra.Accounting.Exchange | Account titles, account classification, and debit and credit operations. |
| Accounting | ExchangeAlgebra.Accounting.TrialBalance, .Entries, .Closing, .Statements, .Consolidation | Bookkeeping procedures; these abbreviated names share the prefix ExchangeAlgebra.Accounting. |
| IO | ExchangeAlgebra.IO.Input, ExchangeAlgebra.IO.Input.Admission, ExchangeAlgebra.IO.Output | External 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.
| Date | Description | Debit | Amount | Credit | Amount |
|---|---|---|---|---|---|
| January 10 | Savings account at Bank A | Cash | 3,000 | Deposits | 3,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:
AccountTitlesis the built-in type of account titles.CashandDepositsare two of its values, andDepositsdenotes savings deposits.Unitis the type that the program declares for units.YenandDollarare units. The valueUnitis 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.
| Division | Not | Hat |
|---|---|---|
| Assets | Increase (debit) | Decrease (credit) |
| Liabilities, equity | Increase (credit) | Decrease (debit) |
| Revenue | Recognition (credit) | Reversal (debit) |
| Expenses | Recognition (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, orSuspenseAccountdepends on the context. The library gives them the same sides as assets:Notis a debit andHatis 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)
decLselects the debit (left) terms, which form the second line of the output.decRselects the credit (right) terms, which form the third line.balancecompares 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:
- Replace the account title with one from Built-in account titles.
- Select
NotorHatfrom Table 2. - Replace
3000with 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:
- To declare or add an element, read Elements.
- To change the combination of elements, read Bases.
- To change the amount type or use other operations, read Redundant and exchange algebras.
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 function | Meaning |
|---|---|
wildcard, or the alias (.#) | The distinguished wildcard value of the inferred type. |
isWildcard x | Whether x equals the whole wildcard value. |
haveWildcard x | Whether x contains a wildcard element, including inside a tuple. |
ignoreWildcard before after | Use 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. |
compareElement | Return EQ for a wildcard match, otherwise compare with the ordinary order. Compare tuples element by element. |
(.<), (.>), (.<=), (.>=), maxElement, minElement | Comparisons and selection using compareElement. |
matchesQuery query entry | One-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. UsematchesQueryto match queries against stored elements or bases. Use ordinary==andcomparefor identity and canonical ordering; wildcard-aware comparison is not a total order on stored values.
Built-in instances
| Type | Wildcard |
|---|---|
AccountTitles | AccountTitle. Import the account type from ExchangeAlgebra or ExchangeAlgebra.Accounting.Account. |
CountUnit | CountUnit; other constructors are Yen, Dollar, Euro, CNY, Amount. |
Text | The empty text. Name and Subject are aliases for Text. You can use Subject to identify which accounting entity a record belongs to. |
Day | ModifiedJulianDay 0 (1858-11-17). To use that date as an ordinary element, use Wild Day. |
TimeOfDay | midnight (00:00). To use 00:00 as an ordinary element, use Wild TimeOfDay. |
Wild a | Wild. Each value x of a is the ordinary element Exactly x. Added in 0.6.1.0. |
| Tuples of 2 through 7 element types | A tuple in which every element is a wildcard. |
Hat | HatNot, for direction patterns. |
HatBase a, for BaseClass a | HatNot :< wildcard. |
BaseForSingleHat | Its 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:
Hatrepresents a direction on a nonnegative amount. The account and direction together determine the debit or credit side. UseHatNotin query patterns. Some direction tests and reversal methods fail onHatNot.
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 method | Purpose |
|---|---|
BasePart a | The base type after removing the direction. For HatBase a, this is a. |
base, hat | Extract the underlying base and direction. |
merge | Build a hat base from a direction and a base part. |
toHat, toNot | Set the direction while retaining the base. |
revHat | Exchange Hat and Not. |
isHat, isNot | Test the direction. |
compareHatBase | Compare 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.
| Methods | Purpose |
|---|---|
zeroValue, isZeroValue | Define zero and test it. isZeroValue has an equality-based default. |
valueError | Return Nothing for a finite nonnegative value, Just NegativeValue for a negative finite value, or Just NonFiniteValue for NaN or either infinity. |
postingUpperBound | An optional bound used by checked term construction. Its default is Nothing; the floating-point instances use a bound of 2^900. |
showValue | Render 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 n | Represent an exact signed sum, including special states if the value type has NaN or infinities. |
emptyAccum, addAccum, mergeAccum, negateAccum | Construct and combine exact sums and differences. |
signAccum, roundAccum, exactAccum | Observe the sign, round once to an amount, or read a finite sum as a Rational. |
splitAccum | Split 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. |
roundRational | Convert 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.
| Operation | Inputs and result |
|---|---|
x .+ y | Retain the terms from both algebras. Equal bases do not cause immediate summation or cancellation. (<>) is the same addition. |
scalar .* x | Multiply every amount by the scalar, preserving the term structure except for zero products. See Construction and scalar checks. |
norm x | Total all stored amounts on both directions. Return an amount, losing base and direction information. |
bar x, also written (.-) x | Total the opposing directions at each full base and keep only the excess on the winning direction. Remove an exactly canceled base. |
compress x | Total each direction at each full base separately, without cancellation. This explicitly discards the separate terms within each direction. |
(.^) x | Swap Hat and Not for every term, preserving each amount. |
proj patterns x | Select terms whose hat bases match at least one query pattern, without netting or changing amounts. |
projNetNorm patterns x | Select 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:
compressdiscards separate term amounts, and floating-point rounding of the direction totals can change the result of a laterbar. Preserve the original algebra when individual terms are needed.
Exchange algebra
| Class or operation | Inputs and result |
|---|---|
ExBaseClass | A HatBaseClass base with account access. Implement getAccountTitle and setAccountTitle; the setter must retain the other elements and direction. |
whatDiv, isContra, whatPIMO, fixedCurrent | Classify an account from its base. The defaults use the account registry. |
whichSide | Return the debit or credit side from account classification and Hat or Not. A query direction HatNot causes an error. |
decL, decR | Select debit (left) or credit (right) terms without changing their amounts or aggregating them. |
decP, decM | decP selects Hat terms; decM selects Not terms. These directions are distinct from debit and credit. |
balance | Compare exact debit and credit sums before rounding, without a tolerance. Return False for non-finite terms. |
diffRL | Return 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
| Operation | Inputs and result |
|---|---|
from .-> to |% Relabel | Move 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 d | Move n/d of the balance, with 0 < n <= d. |
mkTransferTable rows | Validate 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 record | Return Either containing only the additional cancellation and destination terms. Read exact balances; retain the original record by adding the result with .+. |
transferEntriesWith rounding table record | Choose 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 operation | Inputs and result |
|---|---|
Note n | Requires Show, Eq, Ord, Hashable, and Typeable. Define plank; isPlank defaults to equality with plank. |
algebra .| note | Attach one note to all terms of an algebra. A zero algebra produces an empty journal. |
Journal.fromList entries | Sum a list of journals, combining equal note keys with redundant addition. |
Journal.sigma items f | Sum the journals produced by applying f to the items. |
Journal.projWithNote notes journal | Select exact note keys. A list containing plank selects all notes; an empty list selects none. |
Journal.projWithBase bases journal | Select matching terms at every note. Drop a note whose selected algebra is zero. |
Journal.projWithNoteBase notes bases journal | Restrict 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 journal | Keep note-algebra pairs satisfying the predicate. |
Journal.toAlg journal | Remove note keys and add their algebras, retaining term amounts without netting. |
Journal.gather note journal | Put the combined algebra under the specified note, without netting. |
bar journal | Gather under plank, then net the combined algebra. |
Journal.map f journal | Apply 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 operation | Inputs and result |
|---|---|
HatBase (AccountTitles, Owner, Unit) | Identify the account, the accounting entity, and the currency. Direction is separate from the tuple. |
Element Owner | Supply a wildcard element and derive consistent equality, ordering, and hashing. |
ExBaseClass instance | Read 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 combined | Net 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.
asDivisiongives the division. The values areAssetsfor assets,Liabilityfor liabilities,Equityfor equity,Revenuefor revenue, andCostfor expenses.asClosinggives the automatic closing rule.CloseByDivisionuses the division to determine eligibility and transfer direction.NoCloseskips automatic closing for the account.asIsContraidentifies contra accounts, which offset balances in their division.asFixedCurrentclassifies the account asFixed,Current, orOther. For example, revenue and expense accounts useOther.asNameEngives the English name.asNameJagives the Japanese name, which may include notes.asLabelJagives the Japanese display name without notes.asDescriptiongives a description of the account.asAliaseslists the aliases in the registry.accountAliasescombines 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.
asemRoleslists the roles of the account. An account can have multiple roles.OrdinaryAccountmarks an ordinary account,ContraAccountoffsets another balance, andReciprocalAccountmatches balances between entities.SuspenseOrClearingAccountholds amounts temporarily.ClosingDevicesupports closing entries.AttributionAccountassigns amounts to a group.PeriodResultrepresents a period result andReportingSubtotalrepresents a subtotal.asemPostingCapabilitydescribes where the account may be used.OrdinaryPostingallows ordinary entries.ClosingOnly,ConsolidationOnly, andEngineGeneratedOnlylimit use to closing, consolidation, and entries generated by the library, respectively.NotPostablemarks an account unavailable for recording entries.asemDivisionSemanticsexplains what the division represents.StatementDivisiongives a financial statement classification.BookkeepingControlClassgives a class used to control a bookkeeping procedure.DirectionEncodinguses the division to encode direction.NoStatementDivisionindicates that no statement division applies.asemHomeSideSemanticsdescribes the home side, the debit or credit side on which you record an increase in the account.FixedHomeSidespecifiesDebitorCredit.ContextDependentHomeSidedepends on the context.NoFixedHomeSidegives no single home side.NoPostingSidemeans that no posting side applies.asemReportingEligibilitydescribes eligibility for financial statement presentation.StatementEligiblemarks an eligible account.ContextualPresentationdepends on the reporting context.DerivedPresentationrepresents a derived result or subtotal.NotPresentedexcludes 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
ContraAccountrole determines whether a balance is presented as a deduction. - Reading journals from CSV uses
accountAliasesto 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 (
RetainedEarningsandEarnedSurplus) - Supplies (
SuppliesExpensesandSuppliesOnHand) - Central bank payment to treasury (
CentralBankPaymentExpenseandCentralBankPaymentIncome) - Provision for repairs (
AllowanceForRepairsandProvisionForRepairs) - Provision for warranties (
AllowanceForProductWarrantiesandProvisionForProductWarranties) - Provision for bonuses (
AllowanceForBonusesandProvisionForBonuses)
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.
Othercovers 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, includingContraAccountfor 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
| Constructor | English name | Japanese name | Fixed/current | Home side | Closing rule | Roles |
|---|---|---|---|---|---|---|
Cash | Cash | 現金 | Current | FixedHomeSide Debit | CloseByDivision | |
Deposits | Savings deposits | 普通預金 | Current | FixedHomeSide Debit | CloseByDivision | |
CurrentDeposits | Current deposits | 当座預金 | Current | FixedHomeSide Debit | CloseByDivision | |
Securities | Securities | 有価証券 | Current | FixedHomeSide Debit | CloseByDivision | |
InvestmentSecurities | Investment securities | 投資有価証券 | Fixed | FixedHomeSide Debit | CloseByDivision | |
InvestmentInAssociate | Investment in associate | 関係会社株式 | Fixed | FixedHomeSide Debit | CloseByDivision | |
LongTermNationalBonds | Long-term national bonds | 長期国債 | Fixed | FixedHomeSide Debit | CloseByDivision | |
ShortTermNationalBonds | Short-term national bonds | 短期国債 | Current | FixedHomeSide Debit | CloseByDivision | |
Products | Products | 商品 | Current | FixedHomeSide Debit | CloseByDivision | |
Machinery | Machinery and equipment | 機械装置 | Fixed | FixedHomeSide Debit | CloseByDivision | |
Building | Real estate | 建物 | Fixed | FixedHomeSide Debit | CloseByDivision | |
Vehicle | Vehicles | 車両運搬具 | Fixed | FixedHomeSide Debit | CloseByDivision | |
StockInvestment | Stock investment | 株式投資 | Other | FixedHomeSide Debit | CloseByDivision | |
EquipmentInvestment | Equipment investment | 設備投資 | Fixed | FixedHomeSide Debit | CloseByDivision | |
LongTermLoansReceivable | Long-term loans receivable | 長期貸付金 | Fixed | FixedHomeSide Debit | CloseByDivision | |
AccountsReceivable | Accounts receivable | 売掛金 | Current | FixedHomeSide Debit | CloseByDivision | |
ShortTermLoansReceivable | Short-term loans receivable | 短期貸付金 | Current | FixedHomeSide Debit | CloseByDivision | |
ReserveDepositReceivable | Reserve deposits, asset side | 準備預金 | Current | FixedHomeSide Debit | CloseByDivision | |
Gold | Gold | 金 | Fixed | FixedHomeSide Debit | CloseByDivision | |
GovernmentService | Government service | 政府サービス | Current | FixedHomeSide Debit | CloseByDivision | |
PettyCash | Petty cash | 小口現金 | Current | FixedHomeSide Debit | CloseByDivision | |
NotesReceivable | Notes receivable | 受取手形 | Current | FixedHomeSide Debit | CloseByDivision | |
ElectronicallyRecordedReceivable | Electronically recorded monetary claims | 電子記録債権 | Current | FixedHomeSide Debit | CloseByDivision | |
CreditCardReceivable | Credit card receivable | クレジット売掛金 | Current | FixedHomeSide Debit | CloseByDivision | |
NotesLoansReceivable | Loans receivable on notes | 手形貸付金 | Current | FixedHomeSide Debit | CloseByDivision | |
MerchandiseInventory | Merchandise inventory | 繰越商品 | Current | FixedHomeSide Debit | CloseByDivision | |
AdvancesPaid | Advances paid | 前払金 | Current | FixedHomeSide Debit | CloseByDivision | |
PrepaidExpenses | Prepaid expenses | 前払費用 | Current | FixedHomeSide Debit | CloseByDivision | |
AccruedRevenue | Accrued revenue | 未収収益 | Current | FixedHomeSide Debit | CloseByDivision | |
OtherReceivables | Other receivables | 未収入金 | Current | FixedHomeSide Debit | CloseByDivision | |
PaymentsOnBehalf | Payments made on behalf | 立替金 | Current | FixedHomeSide Debit | CloseByDivision | |
SuspensePayments | Suspense payments | 仮払金 | Current | FixedHomeSide Debit | CloseByDivision | SuspenseOrClearingAccount |
ConsumptionTaxPaid | Consumption tax paid | 仮払消費税 | Current | FixedHomeSide Debit | CloseByDivision | |
PrepaidCorporateIncomeTaxes | Prepaid corporate income taxes | 仮払法人税等 | Current | FixedHomeSide Debit | CloseByDivision | |
Land | Land | 土地 | Fixed | FixedHomeSide Debit | CloseByDivision | |
Fixtures | Fixtures and equipment | 備品 | Fixed | FixedHomeSide Debit | CloseByDivision | |
Patent | Patent | 特許権 | Fixed | FixedHomeSide Debit | CloseByDivision | |
Trademark | Trademark | 商標権 | Fixed | FixedHomeSide Debit | CloseByDivision | |
Software | Software | ソフトウェア | Fixed | FixedHomeSide Debit | CloseByDivision | |
CashOverShort | Cash over and short | 現金過不足 | Other | ContextDependentHomeSide | CloseByDivision | SuspenseOrClearingAccount |
AllowanceForDoubtfulAccounts | Allowance for doubtful accounts | 貸倒引当金 | Current | FixedHomeSide Credit | CloseByDivision | ContraAccount |
AccumulatedDepreciation | Accumulated depreciation | 減価償却累計額 | Fixed | FixedHomeSide Credit | CloseByDivision | ContraAccount |
TimeDeposits | Time deposits | 定期預金 | Current | FixedHomeSide Debit | CloseByDivision | |
LoansReceivable | Loans receivable | 貸付金 | Current | FixedHomeSide Debit | CloseByDivision | |
GiftCertificatesReceived | Gift certificates received | 受取商品券 | Current | FixedHomeSide Debit | CloseByDivision | |
SecurityDepositsPaid | Guarantee deposits | 差入保証金 | Fixed | FixedHomeSide Debit | CloseByDivision | |
SuppliesOnHand | Supplies | 貯蔵品 | Current | FixedHomeSide Debit | CloseByDivision | |
ContractAssets | Contract assets | 契約資産 | Current | FixedHomeSide Debit | CloseByDivision | |
IncomeTaxesRefundReceivable | Income taxes refund receivable | 未収還付法人税等 | Current | FixedHomeSide Debit | CloseByDivision | |
WorkInProcess | Work in process | 仕掛品 | Current | FixedHomeSide Debit | CloseByDivision | |
DeferredTaxAssets | Deferred tax assets | 繰延税金資産 | Fixed | FixedHomeSide Debit | CloseByDivision | |
LeasedAssets | Leased assets | リース資産 | Fixed | FixedHomeSide Debit | CloseByDivision | |
ToolsAndInstruments | Tools and instruments | 工具器具 | Fixed | FixedHomeSide Debit | CloseByDivision | |
ConstructionInProgress | Construction in progress | 建設仮勘定 | Fixed | FixedHomeSide Debit | CloseByDivision | |
Goodwill | Goodwill | のれん | Fixed | FixedHomeSide Debit | CloseByDivision | |
SoftwareInProgress | Software in progress | ソフトウェア仮勘定 | Fixed | FixedHomeSide Debit | CloseByDivision | |
LongTermPrepaidExpenses | Long-term prepaid expenses | 長期前払費用 | Fixed | FixedHomeSide Debit | CloseByDivision | |
DishonoredNotesReceivable | Dishonored notes receivable | 不渡手形 | Current | FixedHomeSide Debit | CloseByDivision | |
PrepaidPensionCost | Prepaid pension costs | 前払年金費用 | Fixed | FixedHomeSide Debit | CloseByDivision | |
NetDefinedBenefitAsset | Retirement benefit asset | 退職給付に係る資産 | Fixed | FixedHomeSide Debit | CloseByDivision | |
DepositsInSpecialAccounts | Deposits in special accounts | 別段預金 | Current | FixedHomeSide Debit | CloseByDivision | |
Structures | Structures | 構築物 | Fixed | FixedHomeSide Debit | CloseByDivision | |
LeaseholdRights | Leasehold interests in land | 借地権 | Fixed | FixedHomeSide Debit | CloseByDivision | |
NonOperatingNotesReceivable | Non-operating notes receivable | 営業外受取手形 | Current | FixedHomeSide Debit | CloseByDivision | |
NonOperatingElectronicallyRecordedReceivable | Electronically recorded monetary claims - non-operating | 営業外電子記録債権 | Current | FixedHomeSide Debit | CloseByDivision | |
IncomeSummary | Income summary | 損益 | Other | ContextDependentHomeSide | NoClose | ClosingDevice |
SuspenseAccount | Suspense account | 未決算 | Current | ContextDependentHomeSide | CloseByDivision | SuspenseOrClearingAccount |
ContraAccountForGuaranteeObligations | Contra account for guarantee obligations | 保証債務見返 | Other | FixedHomeSide Debit | CloseByDivision | |
BranchCurrentAccount | Branch current account | 支店 | Other | FixedHomeSide Debit | CloseByDivision | ReciprocalAccount |
TradingSecurities | Trading securities | 売買目的有価証券 | Current | FixedHomeSide Debit | CloseByDivision | |
HeldToMaturityBonds | Held-to-maturity bonds | 満期保有目的債券 | Fixed | FixedHomeSide Debit | CloseByDivision | |
SubsidiaryStocks | Shares of subsidiaries | 子会社株式 | Fixed | FixedHomeSide Debit | CloseByDivision | |
AffiliateStocks | Shares of associates | 関連会社株式 | Fixed | FixedHomeSide Debit | CloseByDivision | |
AvailableForSaleSecurities | Available-for-sale securities | その他有価証券 | Fixed | FixedHomeSide Debit | CloseByDivision | |
ConsumptionTaxRefundReceivable | Consumption tax refund receivable | 未収還付消費税 | Current | FixedHomeSide Debit | CloseByDivision | |
RawMaterials | Raw materials | 原材料 | Current | FixedHomeSide Debit | CloseByDivision | |
GoodsInTransit | Goods in transit | 未着品 | Current | FixedHomeSide Debit | CloseByDivision |
Liabilities
| Constructor | English name | Japanese name | Fixed/current | Home side | Closing rule | Roles |
|---|---|---|---|---|---|---|
LongTermLoansPayable | Long-term loans payable | 長期借入金 | Fixed | FixedHomeSide Credit | CloseByDivision | |
ShortTermLoansPayable | Short-term loans payable | 短期借入金 | Current | FixedHomeSide Credit | CloseByDivision | |
LoansPayable | Loans payable | 借入金 | Current | FixedHomeSide Credit | CloseByDivision | |
ReserveForDepreciation | Reserve for depreciation | 減価償却引当金 | Current | FixedHomeSide Credit | CloseByDivision | |
DepositPayable | Deposits accepted | 受入預金 | Current | FixedHomeSide Credit | CloseByDivision | |
LongTermNationalBondsPayable | Long-term national bonds payable | 長期国債 | Fixed | FixedHomeSide Credit | CloseByDivision | |
ShortTermNationalBondsPayable | Short-term national bonds payable | 短期国債 | Current | FixedHomeSide Credit | CloseByDivision | |
ReserveDepositPayable | Reserve deposits, liability side | 準備預金 | Current | FixedHomeSide Credit | CloseByDivision | |
CentralBankNotePayable | Central bank notes | 発行銀行券 | Current | FixedHomeSide Credit | CloseByDivision | |
AccountsPayable | Accounts payable | 買掛金 | Current | FixedHomeSide Credit | CloseByDivision | |
NotesPayable | Notes payable | 支払手形 | Current | FixedHomeSide Credit | CloseByDivision | |
ElectronicallyRecordedObligations | Electronically recorded monetary obligations | 電子記録債務 | Current | FixedHomeSide Credit | CloseByDivision | |
NotesLoansPayable | Loans payable on notes | 手形借入金 | Current | FixedHomeSide Credit | CloseByDivision | |
BankOverdraft | Bank overdraft | 当座借越 | Current | FixedHomeSide Credit | CloseByDivision | |
AdvancesReceived | Advances received | 前受金 | Current | FixedHomeSide Credit | CloseByDivision | |
UnearnedRevenue | Unearned revenue | 前受収益 | Current | FixedHomeSide Credit | CloseByDivision | |
AccruedExpenses | Accrued expenses | 未払費用 | Current | FixedHomeSide Credit | CloseByDivision | |
OtherPayables | Other payables | 未払金 | Current | FixedHomeSide Credit | CloseByDivision | |
DepositsReceived | Deposits received | 預り金 | Current | FixedHomeSide Credit | CloseByDivision | |
SuspenseReceipts | Suspense receipts | 仮受金 | Current | FixedHomeSide Credit | CloseByDivision | SuspenseOrClearingAccount |
ConsumptionTaxReceived | Consumption tax received | 仮受消費税 | Current | FixedHomeSide Credit | CloseByDivision | |
AccruedConsumptionTax | Accrued (unpaid) consumption tax | 未払消費税 | Current | FixedHomeSide Credit | CloseByDivision | |
AccruedCorporateIncomeTaxes | Accrued (unpaid) corporate income taxes | 未払法人税等 | Current | FixedHomeSide Credit | CloseByDivision | |
UnpaidDividends | Unpaid dividends | 未払配当金 | Current | FixedHomeSide Credit | CloseByDivision | |
RefundLiabilities | Refund liabilities | 返金負債 | Current | FixedHomeSide Credit | CloseByDivision | |
NonOperatingNotesPayable | Non-operating notes payable | 営業外支払手形 | Current | FixedHomeSide Credit | CloseByDivision | |
NonOperatingElectronicallyRecordedObligations | Electronically recorded obligations - non-operating | 営業外電子記録債務 | Current | FixedHomeSide Credit | CloseByDivision | |
BonusesPayable | Accrued bonuses | 未払賞与 | Current | FixedHomeSide Credit | CloseByDivision | |
AllowanceForRepairs | Provision for repairs | 修繕引当金 | Current | FixedHomeSide Credit | CloseByDivision | |
AllowanceForProductWarranties | Provision for warranties | 商品保証引当金 | Current | FixedHomeSide Credit | CloseByDivision | |
AllowanceForBonuses | Provision for bonuses | 賞与引当金 | Current | FixedHomeSide Credit | CloseByDivision | |
DeferredTaxLiabilities | Deferred tax liabilities | 繰延税金負債 | Fixed | FixedHomeSide Credit | CloseByDivision | |
LeaseObligations | Lease liabilities | リース債務 | Fixed | FixedHomeSide Credit | CloseByDivision | |
GuaranteeDepositsReceived | Guarantee deposits received | 預り保証金 | Fixed | FixedHomeSide Credit | CloseByDivision | |
AllowanceForRetirementBenefits | Provision for retirement benefits | 退職給付引当金 | Fixed | FixedHomeSide Credit | CloseByDivision | |
LongTermOtherPayables | Long-term accounts payable - other | 長期未払金 | Fixed | FixedHomeSide Credit | CloseByDivision | |
NetDefinedBenefitLiability | Retirement benefit liability | 退職給付に係る負債 | Fixed | FixedHomeSide Credit | CloseByDivision | |
GuaranteeObligations | Guarantee obligations | 保証債務 | Other | FixedHomeSide Credit | CloseByDivision | |
HeadOfficeCurrentAccount | Head office current account | 本店 | Other | FixedHomeSide Credit | CloseByDivision | ReciprocalAccount |
PropertyTaxPayable | Property tax payable | 未払固定資産税 | Current | FixedHomeSide Credit | CloseByDivision | |
DepositsReceivedFromOfficers | Deposits received from officers | 役員預り金 | Current | FixedHomeSide Credit | CloseByDivision |
Equity
| Constructor | English name | Japanese name | Fixed/current | Home side | Closing rule | Roles |
|---|---|---|---|---|---|---|
CapitalStock | Capital stock | 資本金 | Other | FixedHomeSide Credit | CloseByDivision | |
RetainedEarnings | Retained earnings | 繰越利益剰余金 | Other | FixedHomeSide Credit | CloseByDivision | |
LegalRetainedEarnings | Legal (appropriated) retained earnings reserve | 利益準備金 | Other | FixedHomeSide Credit | CloseByDivision | |
CumulativeTranslationAdjustment | Cumulative translation adjustment | 為替換算調整勘定 | Other | FixedHomeSide Credit | CloseByDivision | |
StockSubscriptionDeposits | Deposits for subscriptions of shares | 株式申込証拠金 | Other | FixedHomeSide Credit | CloseByDivision | |
LegalCapitalSurplus | Legal capital surplus | 資本準備金 | Other | FixedHomeSide Credit | CloseByDivision | |
OtherCapitalSurplus | Other capital surplus | その他資本剰余金 | Other | FixedHomeSide Credit | CloseByDivision | |
DividendEqualizationReserve | Reserve for dividend equalization | 配当平均積立金 | Other | FixedHomeSide Credit | CloseByDivision | |
RepairFundReserve | Reserve for repairs | 修繕積立金 | Other | FixedHomeSide Credit | CloseByDivision | |
ConstructionFundReserve | Reserve for new construction | 新築積立金 | Other | FixedHomeSide Credit | CloseByDivision | |
GeneralReserve | General reserve | 別途積立金 | Other | FixedHomeSide Credit | CloseByDivision | |
ValuationDifferenceOnOtherSecurities | Valuation difference on available-for-sale securities | その他有価証券評価差額金 | Other | FixedHomeSide Credit | CloseByDivision | |
NonControllingInterests | Non-controlling interests | 非支配株主持分 | Other | FixedHomeSide Credit | CloseByDivision | AttributionAccount |
CapitalSurplus | Capital surplus | 資本剰余金 | Other | FixedHomeSide Credit | CloseByDivision | |
EarnedSurplus | Retained earnings | 利益剰余金 | Other | FixedHomeSide Credit | CloseByDivision |
Revenue
| Constructor | English name | Japanese name | Fixed/current | Home side | Closing rule | Roles |
|---|---|---|---|---|---|---|
ValueAdded | Value added | 付加価値 | Other | FixedHomeSide Credit | CloseByDivision | |
SubsidyIncome | Subsidy income | 補助金収入 | Other | FixedHomeSide Credit | CloseByDivision | |
NationalBondInterestEarned | National bond interest earned | 国債利息収入 | Other | FixedHomeSide Credit | CloseByDivision | |
DepositInterestEarned | Deposit interest earned | 預金利息収入 | Other | FixedHomeSide Credit | CloseByDivision | |
GrossProfit | Gross profit | 売上総利益 | Other | FixedHomeSide Credit | CloseByDivision | ReportingSubtotal |
OrdinaryProfit | Ordinary profit | 経常利益 | Other | FixedHomeSide Credit | CloseByDivision | ReportingSubtotal |
InterestEarned | Interest earned | 受取利息 | Other | FixedHomeSide Credit | CloseByDivision | |
ReceiptFee | Receipt fee | 受取手数料 | Other | FixedHomeSide Credit | CloseByDivision | |
RentalIncome | Rental income | 受取家賃 | Other | FixedHomeSide Credit | CloseByDivision | |
WageEarned | Wage income | 賃金収入 | Other | FixedHomeSide Credit | CloseByDivision | |
TaxesRevenue | Tax revenue | 租税収入 | Other | FixedHomeSide Credit | CloseByDivision | |
CentralBankPaymentIncome | Central bank payment to treasury | 国庫納付金収入 | Other | FixedHomeSide Credit | CloseByDivision | |
Sales | Sales | 売上 | Other | FixedHomeSide Credit | CloseByDivision | |
EquityInEarningsOfInvestee | Equity in earnings of investee | 持分法による投資利益 | Other | FixedHomeSide Credit | CloseByDivision | |
NetLoss | Net loss | 当期純損失 | Other | FixedHomeSide Credit | NoClose | PeriodResult |
GainOnSalesOfFixedAssets | Gain on sales of fixed assets | 固定資産売却益 | Other | FixedHomeSide Credit | CloseByDivision | |
RecoveryOfBadDebts | Recovery of bad debts written off | 償却債権取立益 | Other | FixedHomeSide Credit | CloseByDivision | |
MiscellaneousIncome | Miscellaneous income | 雑益 | Other | FixedHomeSide Credit | CloseByDivision | |
ReversalOfAllowanceForDoubtfulAccounts | Reversal of allowance for doubtful accounts | 貸倒引当金戻入 | Other | FixedHomeSide Credit | CloseByDivision | |
ServiceRevenue | Service revenue | 役務収益 | Other | FixedHomeSide Credit | CloseByDivision | |
OperatingRevenue | Operating revenue | 営業収益 | Other | FixedHomeSide Credit | CloseByDivision | |
GainOnSalesOfSecurities | Gain on sale of securities | 有価証券売却益 | Other | FixedHomeSide Credit | CloseByDivision | |
GainOnValuationOfSecurities | Gain on valuation of securities | 有価証券評価益 | Other | FixedHomeSide Credit | CloseByDivision | |
DividendsReceived | Dividend income | 受取配当金 | Other | FixedHomeSide Credit | CloseByDivision | |
InterestOnSecurities | Interest on securities | 有価証券利息 | Other | FixedHomeSide Credit | CloseByDivision | |
GainOnSalesOfInvestmentSecurities | Gain on sale of investment securities | 投資有価証券売却益 | Other | FixedHomeSide Credit | CloseByDivision | |
InsuranceGain | Gain on insurance claims | 保険差益 | Other | FixedHomeSide Credit | CloseByDivision | |
GainOnBargainPurchase | Gain on bargain purchase | 負ののれん発生益 | Other | FixedHomeSide Credit | CloseByDivision | |
ReversalOfAllowanceForRepairs | Reversal of provision for repairs | 修繕引当金戻入 | Other | FixedHomeSide Credit | CloseByDivision | |
ReversalOfAllowanceForProductWarranties | Reversal of provision for warranties | 商品保証引当金戻入 | Other | FixedHomeSide Credit | CloseByDivision | |
GainOnDonationOfFixedAssets | Gain on receipt of donated non-current assets | 固定資産受贈益 | Other | FixedHomeSide Credit | CloseByDivision | |
GainOnNationalSubsidies | Gain on receipt of national subsidies | 国庫補助金受贈益 | Other | FixedHomeSide Credit | CloseByDivision | |
GainOnConstructionGrants | Gain on contribution received for construction | 工事負担金受贈益 | Other | FixedHomeSide Credit | CloseByDivision | |
LandRentReceived | Rental income from land | 受取地代 | Other | FixedHomeSide Credit | CloseByDivision | |
SalesRebates | Sales rebates | 売上割戻 | Other | FixedHomeSide Debit | CloseByDivision | ContraAccount |
ForeignExchangeGains | Foreign exchange gains | 為替差益 | Other | FixedHomeSide Credit | CloseByDivision | |
NetLossAttributableToNCI | Loss attributable to non-controlling interests | 非支配株主に帰属する当期純損失 | Other | FixedHomeSide Credit | NoClose | AttributionAccount, PeriodResult |
SalesAllowances | Sales allowances | 売上値引 | Other | FixedHomeSide Debit | CloseByDivision | ContraAccount |
ReversalOfAllowanceForBonuses | Reversal of provision for bonuses | 賞与引当金戻入 | Other | FixedHomeSide Credit | CloseByDivision |
Expenses
| Constructor | English name | Japanese name | Fixed/current | Home side | Closing rule | Roles |
|---|---|---|---|---|---|---|
Depreciation | Depreciation | 減価償却費 | Other | FixedHomeSide Debit | CloseByDivision | |
AmortizationExpense | Amortization expense for intangibles | 無形固定資産償却費 | Other | FixedHomeSide Debit | CloseByDivision | |
SalesCost | Cost of sales | 売上原価 | Other | FixedHomeSide Debit | CloseByDivision | |
BusinessTrip | Travel and transportation | 旅費交通費 | Other | FixedHomeSide Debit | CloseByDivision | |
Commutation | Communication | 通信費 | Other | FixedHomeSide Debit | CloseByDivision | |
UtilitiesExpense | Utilities | 水道光熱費 | Other | FixedHomeSide Debit | CloseByDivision | |
RentExpense | Rent | 支払家賃 | Other | FixedHomeSide Debit | CloseByDivision | |
AdvertisingExpense | Advertising | 広告宣伝費 | Other | FixedHomeSide Debit | CloseByDivision | |
DeliveryExpenses | Delivery | 発送費 | Other | FixedHomeSide Debit | CloseByDivision | |
SuppliesExpenses | Supplies | 消耗品費 | Other | FixedHomeSide Debit | CloseByDivision | |
MiscellaneousExpenses | Miscellaneous | 雑費 | Other | FixedHomeSide Debit | CloseByDivision | |
WageExpenditure | Wages | 給料 | Other | FixedHomeSide Debit | CloseByDivision | |
InterestExpense | Interest expense | 支払利息 | Other | FixedHomeSide Debit | CloseByDivision | |
TaxesExpense | Taxes | 租税公課 | Other | FixedHomeSide Debit | CloseByDivision | |
ConsumptionExpenditure | Consumption expenditure | 消費支出 | Other | FixedHomeSide Debit | CloseByDivision | |
SubsidyExpense | Subsidy expenditure | 補助金支出 | Other | FixedHomeSide Debit | CloseByDivision | |
CentralBankPaymentExpense | Central bank payment to treasury | 国庫納付金支出 | Other | FixedHomeSide Debit | CloseByDivision | |
Purchases | Purchases | 仕入 | Other | FixedHomeSide Debit | CloseByDivision | |
NetIncome | Net income | 当期純利益 | Other | FixedHomeSide Debit | NoClose | PeriodResult |
ProvisionForDoubtfulAccounts | Provision for doubtful accounts | 貸倒引当金繰入 | Other | FixedHomeSide Debit | CloseByDivision | |
BadDebtLoss | Bad debt loss | 貸倒損失 | Other | FixedHomeSide Debit | CloseByDivision | |
LossOnSalesOfFixedAssets | Loss on sales of fixed assets | 固定資産売却損 | Other | FixedHomeSide Debit | CloseByDivision | |
LossOnSalesOfNotesReceivable | Loss on sales of notes receivable | 手形売却損 | Other | FixedHomeSide Debit | CloseByDivision | |
PaymentFees | Payment fees / fees paid | 支払手数料 | Other | FixedHomeSide Debit | CloseByDivision | |
MiscellaneousLoss | Miscellaneous loss | 雑損 | Other | FixedHomeSide Debit | CloseByDivision | |
CorporateIncomeTaxes | Corporate income taxes | 法人税等 | Other | FixedHomeSide Debit | CloseByDivision | |
CommunicationExpenses | Communication expenses | 通信費 | Other | FixedHomeSide Debit | CloseByDivision | |
CostOfServices | Cost of services | 役務原価 | Other | FixedHomeSide Debit | CloseByDivision | |
OperatingExpenses | Operating expenses | 営業費用 | Other | FixedHomeSide Debit | CloseByDivision | |
InventoryShrinkageLoss | Inventory shrinkage loss | 棚卸減耗損 | Other | FixedHomeSide Debit | CloseByDivision | |
LossOnValuationOfMerchandise | Valuation loss on goods | 商品評価損 | Other | FixedHomeSide Debit | CloseByDivision | |
Bonuses | Bonuses | 賞与 | Other | FixedHomeSide Debit | CloseByDivision | |
RetirementBenefitExpenses | Retirement benefit expenses | 退職給付費用 | Other | FixedHomeSide Debit | CloseByDivision | |
ProvisionForRepairs | Provision for repairs | 修繕引当金繰入 | Other | FixedHomeSide Debit | CloseByDivision | |
ProvisionForBonuses | Provision for bonuses | 賞与引当金繰入 | Other | FixedHomeSide Debit | CloseByDivision | |
ProvisionForProductWarranties | Provision for warranties | 商品保証引当金繰入 | Other | FixedHomeSide Debit | CloseByDivision | |
ResearchAndDevelopmentExpenses | Research and development expenses | 研究開発費 | Other | FixedHomeSide Debit | CloseByDivision | |
AmortizationOfGoodwill | Amortization of goodwill | のれん償却 | Other | FixedHomeSide Debit | CloseByDivision | |
AmortizationOfSoftware | Amortization of software | ソフトウェア償却 | Other | FixedHomeSide Debit | CloseByDivision | |
AmortizationOfPatents | Amortization of patent rights | 特許権償却 | Other | FixedHomeSide Debit | CloseByDivision | |
LeaseExpenses | Lease expenses | 支払リース料 | Other | FixedHomeSide Debit | CloseByDivision | |
IncorporationExpenses | Organization expenses | 創立費 | Other | FixedHomeSide Debit | CloseByDivision | |
StockIssuanceCosts | Share issuance costs | 株式交付費 | Other | FixedHomeSide Debit | CloseByDivision | |
BusinessCommencementExpenses | Business commencement expenses | 開業費 | Other | FixedHomeSide Debit | CloseByDivision | |
DevelopmentExpenses | Development expenses | 開発費 | Other | FixedHomeSide Debit | CloseByDivision | |
LossOnSalesOfElectronicallyRecordedReceivables | Loss on sale of electronically recorded monetary claims | 電子記録債権売却損 | Other | FixedHomeSide Debit | CloseByDivision | |
LossOnSalesOfReceivables | Loss on sale of receivables | 債権売却損 | Other | FixedHomeSide Debit | CloseByDivision | |
LossOnSalesOfSecurities | Loss on sale of securities | 有価証券売却損 | Other | FixedHomeSide Debit | CloseByDivision | |
LossOnValuationOfSecurities | Loss on valuation of securities | 有価証券評価損 | Other | FixedHomeSide Debit | CloseByDivision | |
LossOnSalesOfInvestmentSecurities | Loss on sale of investment securities | 投資有価証券売却損 | Other | FixedHomeSide Debit | CloseByDivision | |
LossOnFire | Loss on fire | 火災損失 | Other | FixedHomeSide Debit | CloseByDivision | |
LossOnRetirementOfFixedAssets | Loss on retirement of non-current assets | 固定資産除却損 | Other | FixedHomeSide Debit | CloseByDivision | |
LossOnReductionOfFixedAssets | Loss on tax purpose reduction entry of non-current assets | 固定資産圧縮損 | Other | FixedHomeSide Debit | CloseByDivision | |
AdditionalIncomeTaxesForPriorPeriods | Additional income taxes for prior periods | 追徴法人税等 | Other | FixedHomeSide Debit | CloseByDivision | |
RefundOfIncomeTaxes | Refund of income taxes | 還付法人税等 | Other | FixedHomeSide Credit | CloseByDivision | ContraAccount |
PurchaseRebates | Purchase rebates | 仕入割戻 | Other | FixedHomeSide Credit | CloseByDivision | ContraAccount |
WelfareExpenses | Welfare expenses | 福利厚生費 | Other | FixedHomeSide Debit | CloseByDivision | |
MaintenanceExpenses | Maintenance expenses | 保守費 | Other | FixedHomeSide Debit | CloseByDivision | |
StatutoryWelfareExpenses | Legal welfare expenses | 法定福利費 | Other | FixedHomeSide Debit | CloseByDivision | |
LandRentPaid | Rent expenses on land | 支払地代 | Other | FixedHomeSide Debit | CloseByDivision | |
InsuranceExpense | Insurance expenses | 保険料 | Other | FixedHomeSide Debit | CloseByDivision | |
RepairsExpense | Repair expenses | 修繕費 | Other | FixedHomeSide Debit | CloseByDivision | |
StorageExpenses | Storage costs | 保管費 | Other | FixedHomeSide Debit | CloseByDivision | |
MembershipFees | Membership fees | 諸会費 | Other | FixedHomeSide Debit | CloseByDivision | |
ForeignExchangeLosses | Foreign exchange losses | 為替差損 | Other | FixedHomeSide Debit | CloseByDivision | |
IncomeTaxesAdjustment | Income taxes - deferred | 法人税等調整額 | Other | FixedHomeSide Debit | CloseByDivision | |
NetIncomeAttributableToNCI | Profit attributable to non-controlling interests | 非支配株主に帰属する当期純利益 | Other | FixedHomeSide Debit | NoClose | AttributionAccount, PeriodResult |
EntertainmentExpenses | Entertainment expenses | 交際費 | Other | FixedHomeSide Debit | CloseByDivision | |
MeetingExpenses | Meeting expenses | 会議費 | Other | FixedHomeSide Debit | CloseByDivision | |
NewspaperBooksExpenses | Newspapers and books | 新聞図書費 | Other | FixedHomeSide Debit | CloseByDivision | |
PurchaseAllowances | Purchase allowances | 仕入値引 | Other | FixedHomeSide Credit | CloseByDivision | ContraAccount |
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 operation | Inputs and result |
|---|---|
Admission.admit journal | Check every note; return an input error report or an Admitted journal. |
Admission.admittedJournal accepted | Recover the journal without netting or changing its notes. |
Admission.failureErrors failure | Read input errors in ascending note order. |
Algebra.mapPosting f algebra | Transform 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 operation | Inputs and result |
|---|---|
TrialBalance.accountBalances ledger | Compute account balances across all supplied terms. |
TrialBalance.balanceFor account balances | Read an account; an absent account returns NoBalance. |
TrialBalance.balancePair balance | Return a pair ordered as debit balance, then credit balance. |
TrialBalance.trialBalanceFindings input | Report 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 operation | Inputs and result |
|---|---|
Entries.MkBase b | A function from Hat/Not and account title to the chosen base. |
Entries.cogsAdjustmentEntries mk beginning ending | Return the periodic inventory adjustment; supply non-negative finite amounts in the same unit. |
transferEntries table ledger | Return 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 operation | Inputs and result |
|---|---|
Closing.closingEntries ledger | Return additional entries to RetainedEarnings, or Left for an invalid eligible balance. |
TrialBalance.AfterClosing | Check the post-closing trial balance, including unclosed revenue and expense accounts. |
additions .| note and journal .+ closingJournal | Attach 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 operation | Inputs and result |
|---|---|
present context stage ledger | Prepare statement lines, subtotals, and presentation events. BeforeClosing includes the period result. Use trialBalanceFindings separately to inspect accounting findings. |
jcciSecondGradeContext scope and PresentationProfile | Start with the JCCI grade-2 profile. Set _presentationProfile to CanonicalJapanese or CanonicalEnglish to use canonical labels. |
ReportingContext | Supply 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 ledger | Derive PeriodProfit, PeriodLoss, or PeriodBreakEven from a before-closing ledger. AfterClosing returns MetricNotAvailableAtStage. |
defaultPresentationGrouping and presentGroups | For 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))
Link the statement columns
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 operation | Inputs and result |
|---|---|
TrialBalanceSource | Identify one entity and supply its balanced trial balance over HatBase AccountTitles. |
WorksheetAdjustment | Supply an independently balanced adjustment with its own ID and the nonempty list of source IDs it affects. |
WorksheetLinkage | Supply the period result and its attribution, and reconcile opening balances, period movements, dividends, and closing balances for retained earnings and noncontrolling interests. |
validateConsolidationWorksheet input | Validate the worksheet or return a nonempty list of WorksheetError values identifying the rejected inputs. |
combinedWorksheet, validatedSources, and validatedAdjustments | Project 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 operation | Inputs and result |
|---|---|
parseJournalCsv and parseNotedJournalCsv | Parse 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 parseAccountTitle | Normalize names for lookup and resolve them to account titles. A name with several matches returns AmbiguousAccount and its candidates. |
checkedJournal | Build an ordinary journal from keyed entries with resolved titles. Duplicate keys and invalid entries produce journal errors. |
certifyJournalText | Certify entries supplied as side text, account text, and amount. The result is FullyResolved, BalancedUnresolved, or Rejected. |
reconcileSources | Compare the transaction identifiers and amounts supplied by the reconciliation source with the journal. |
admit | Check 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 operation | Inputs and result |
|---|---|
journalRows and writeJournal | Lay out a journal by day from terms and a date accessor. The writer saves the rows to a path. |
accountLedgerRows and writeAccountOf | Lay out a general ledger for the requested accounts from dated terms. |
compoundTrialBalanceRows and writeCompoundTrialBalance | Lay out debit and credit totals and net balances from one ledger. |
worksheetRows and writeWorksheet | Lay out the eight-column worksheet from a pre-adjustment ledger and separate adjusting entries. |
postClosingTrialBalanceRows and writePostClosingTrialBalance | Lay out the balances carried forward from a closed ledger. |
financialStatementRows and writeFinancialStatements | Render the requested sections of FinancialStatements. A request for revenue or expenses without a period-result subtotal returns PeriodResultMissing. |
ExchangeAlgebra.IO.Output.Csv.writeCSV | Write a table of text cells to a file. Every cell is quoted, and embedded quotation marks are doubled. |