Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Checking a journal

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

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

Prepare the January records

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

Code carried over from earlier chapters

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

module Main where

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

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

instance Element Unit where
    wildcard = Unit

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

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

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

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

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

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

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

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

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

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

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

Express dollar cash in yen

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

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

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

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

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

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

Check the January journal

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

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

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

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

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

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

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

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

Reference

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