Reading journals from CSV
Import the shop’s January 28 cash sale and January 30 rent payment from CSV. Both transactions are in yen, so the input uses HatBase AccountTitles with the currency fixed for the file. The accepted journal retains a separate note for each transaction.
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.
Write one CSV row per term
Save the CSV as january-import.csv in the same directory as Main.hs. The header gives the journal side, account title, amount, and optional note. Use debit or credit for the side and an unsigned decimal amount without thousands separators. Use the same nonempty note for every term in one transaction and a distinct note for each other transaction. The parser trims spaces around fields and skips blank lines and comment lines starting with # after whitespace. Commas always separate fields, so keep commas out of the notes.
side,account,amount,note
debit,Cash,2000,Jan 28 Cash sale
credit,Sales,2000,Jan 28 Cash sale
debit,RentExpense,1200,Jan 30 January and February rent
credit,Cash,1200,Jan 30 January and February rent
For each line, the CSV parser resolves the account with parseAccountTitle. It accepts canonical English names and registered aliases. normalizeTitle lowercases the text, removes punctuation, and collapses whitespace before lookup. For example, A/R normalizes to ar and resolves to AccountsReceivable.
See Account titles and their attributes for the sources of the registered aliases.
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.List (groupBy, sortOn)
import Data.String (IsString, fromString)
import ExchangeAlgebra (AccountTitles(..), Alg, HatBase, MoneyDecimal, Side(..), decL, decR, norm)
import qualified ExchangeAlgebra.IO.Input as Input
import qualified ExchangeAlgebra.IO.Input.Admission as Admission
import qualified ExchangeAlgebra.IO.Input.Csv as Csv
import qualified ExchangeAlgebra.Journal as Journal
Code carried over from earlier chapters
-- | Stop the example on an unexpected checked failure.
require :: Show e => Either e a -> IO a
require = either (ioError . userError . show) pure
Check the imported journal
parseJournalCsv returns one algebra value with all the parsed terms. Its debit and credit totals describe the file as a whole. To check transactions individually, use parseNotedJournalCsv to retain the note column. Group the rows by note and pass one group per transaction to checkedJournal. It checks each group’s accounts, term amounts, and debit and credit totals before constructing the journal.
-- | Group the parsed terms by transaction key, keeping the order within each entry.
groupTransactions :: Ord note
=> [(Side, AccountTitles, MoneyDecimal, note)]
-> [(note, [(Side, AccountTitles, MoneyDecimal)])]
groupTransactions rows =
[ (note, map withoutNote entry)
| entry@((_, _, _, note) : _) <- groupBy sameNote (sortOn noteOf rows)
]
where
noteOf (_, _, _, note) = note
sameNote left right = noteOf left == noteOf right
withoutNote (side, account, amount, _) = (side, account, amount)
-- | Require a transaction key on every CSV term before grouping by note.
checkNotes :: (Eq note, IsString note)
=> [(Side, AccountTitles, MoneyDecimal, note)] -> Either String ()
checkNotes rows
| any (\(_, _, _, note) -> note == "") rows = Left "Missing transaction key in note"
| otherwise = Right ()
Compare the checked journal with the amounts from the sale and rent records using reconcileSources. It reports absent or unexpected transaction keys and compares the expected amount for each key with its debit total. Pass the journal to admit to obtain the Admitted value described in Checking a journal.
main :: IO ()
main = do
input <- fromString <$> readFile "january-import.csv"
flat <- require (Csv.parseJournalCsv input :: Either Input.ConvError
(Alg MoneyDecimal (HatBase AccountTitles)))
putStrLn $ "Parsed term totals (debit, credit): "
++ show (norm (decL flat), norm (decR flat))
rows <- require (Csv.parseNotedJournalCsv Csv.scientificAmount input)
require (checkNotes rows)
journal <- require (Input.checkedJournal (groupTransactions rows))
let sources = [("Jan 28 Cash sale", 2000), ("Jan 30 January and February rent", 1200)]
differences = Input.reconcileSources sources journal
case differences of
[] -> pure ()
_ -> ioError (userError (show differences))
accepted <- require (Admission.admit journal)
let ledger = Journal.toAlg (Admission.admittedJournal accepted)
putStrLn $ "Source differences: " ++ show differences
putStrLn $ "Admitted journal totals (debit, credit): "
++ show (norm (decL ledger), norm (decR ledger))
printDiagnostics
Diagnose an unknown title and an unbalanced entry
If the sale credit is spelled Saels, the CSV parser returns UnknownAccount. For sources already represented as text triples, certifyJournalText can report a balanced transaction with an unresolved name as BalancedUnresolved. Correct the name before submitting the journal for checking. If the sale credit is 1,900 yen against a 2,000-yen debit, checkedJournal reports Imbalanced under the sale’s transaction key.
-- | Show the results of a misspelled title and a separate amount error.
printDiagnostics :: IO ()
printDiagnostics = do
putStrLn $ "Normalized title: " ++ show (Input.normalizeTitle " A/R ")
putStrLn $ "Account name: " ++ show (Input.parseAccountTitle " A/R ")
let typoCsv = "side,account,amount\ndebit,Cash,2000\ncredit,Saels,2000\n"
putStrLn $ "CSV title error: "
++ show (Csv.parseJournalCsv typoCsv :: Either Input.ConvError
(Alg MoneyDecimal (HatBase AccountTitles)))
let unresolved = Input.certifyJournalText
[("Jan 28 Cash sale" :: String, [("debit", "Cash", 2000 :: MoneyDecimal),
("credit", "Saels", 2000)])]
putStrLn $ "Text certification: " ++ show unresolved
let unbalanced = Input.checkedJournal
[("Jan 28 Cash sale" :: String, [(Debit, Cash, 2000 :: MoneyDecimal),
(Credit, Sales, 1900)])]
putStrLn $ "Entry balance error: " ++ show unbalanced
In your project directory, run stack exec -- ghc -Wall -Werror Main.hs -o input-example, then run ./input-example.
Parsed term totals (debit, credit): (3200,3200)
Source differences: []
Admitted journal totals (debit, credit): (3200,3200)
Normalized title: "ar"
Account name: Right AccountsReceivable
CSV title error: Left (UnknownAccount "Saels")
Text certification: BalancedUnresolved {_certResolved = [("Jan 28 Cash sale",[(Debit,Cash,2000)])], _certUnresolved = [("Jan 28 Cash sale",[(1,"Saels",UnknownAccount "Saels")])], _certDebitTotal = 2000, _certCreditTotal = 2000}
Entry balance error: Left (EntryErrors "Jan 28 Cash sale" (Imbalanced {_debitTotal = 2000, _creditTotal = 1900} :| []) :| [])
The checked journal’s debit and credit totals are both 3,200 yen, and the source comparison returns an empty list. The name and amount errors come from the separate diagnostic examples.
Tested with exchangealgebra-0.6.1.1 on 2026-11-20.
Reference
| Type or operation | Inputs and result |
|---|---|
parseJournalCsv and parseNotedJournalCsv | Parse fixed-schema CSV. The former returns one algebra value. The latter takes an amount parser such as scientificAmount and returns individual rows with notes. |
normalizeTitle and parseAccountTitle | Normalize names for lookup and resolve them to account titles. A name with several matches returns AmbiguousAccount and its candidates. |
checkedJournal | Build an ordinary journal from keyed entries with resolved titles. Duplicate keys and invalid entries produce journal errors. |
certifyJournalText | Certify entries supplied as side text, account text, and amount. The result is FullyResolved, BalancedUnresolved, or Rejected. |
reconcileSources | Compare the transaction identifiers and amounts supplied by the reconciliation source with the journal. |
admit | Check the journal at the note level and return an Admitted value on success. |