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