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