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. |