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

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.

MethodsPurpose
zeroValue, isZeroValueDefine zero and test it. isZeroValue has an equality-based default.
valueErrorReturn Nothing for a finite nonnegative value, Just NegativeValue for a negative finite value, or Just NonFiniteValue for NaN or either infinity.
postingUpperBoundAn optional bound used by checked term construction. Its default is Nothing; the floating-point instances use a bound of 2^900.
showValueRender 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 nRepresent an exact signed sum, including special states if the value type has NaN or infinities.
emptyAccum, addAccum, mergeAccum, negateAccumConstruct and combine exact sums and differences.
signAccum, roundAccum, exactAccumObserve the sign, round once to an amount, or read a finite sum as a Rational.
splitAccumSplit 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.
roundRationalConvert 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.

OperationInputs and result
x .+ yRetain the terms from both algebras. Equal bases do not cause immediate summation or cancellation. (<>) is the same addition.
scalar .* xMultiply every amount by the scalar, preserving the term structure except for zero products. See Construction and scalar checks.
norm xTotal all stored amounts on both directions. Return an amount, losing base and direction information.
bar x, also written (.-) xTotal the opposing directions at each full base and keep only the excess on the winning direction. Remove an exactly canceled base.
compress xTotal each direction at each full base separately, without cancellation. This explicitly discards the separate terms within each direction.
(.^) xSwap Hat and Not for every term, preserving each amount.
proj patterns xSelect terms whose hat bases match at least one query pattern, without netting or changing amounts.
projNetNorm patterns xSelect 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: compress discards separate term amounts, and floating-point rounding of the direction totals can change the result of a later bar. Preserve the original algebra when individual terms are needed.

Exchange algebra

Class or operationInputs and result
ExBaseClassA HatBaseClass base with account access. Implement getAccountTitle and setAccountTitle; the setter must retain the other elements and direction.
whatDiv, isContra, whatPIMO, fixedCurrentClassify an account from its base. The defaults use the account registry.
whichSideReturn the debit or credit side from account classification and Hat or Not. A query direction HatNot causes an error.
decL, decRSelect debit (left) or credit (right) terms without changing their amounts or aggregating them.
decP, decMdecP selects Hat terms; decM selects Not terms. These directions are distinct from debit and credit.
balanceCompare exact debit and credit sums before rounding, without a tolerance. Return False for non-finite terms.
diffRLReturn 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.