Skip to content

Ledger

Print a ledger of dated entries as a fixed-width table, with dates and amounts in American or Dutch style.

Adapted from Exercism’s problem specification (MIT). Listed under Strings & Text.

// FILE: ledger.nomi
//# Prints a ledger of dated entries as a table, in American or Dutch style.

import
    std::calendar.{Date, DateFields}
    std::currency.Currency
    std::money.{CurrencySign, Money}
end

/// One line of the ledger: when, what for, and the change in cents, negative
/// for money spent.
pub struct Entry
    date:        Date
    description: String
    cents:       Int
end

/// The two styles the ledger is printed in: their headings, dates and amounts.
pub enum Style
    American
    Dutch
end

impl Style
    fn locale(style: Style) -> Locale
        case style
            .American -> Locale"en-US"
            .Dutch    -> Locale"nl-NL"
        end
    end

    /// How the style writes a negative amount: American style as an
    /// accountant does, in parentheses.
    fn sign(style: Style) -> CurrencySign
        case style
            .American -> .Accounting
            .Dutch    -> .Standard
        end
    end

    fn headings(style: Style) -> (String, String, String)
        case style
            .American -> ("Date", "Description", "Change")
            .Dutch    -> ("Datum", "Omschrijving", "Verandering")
        end
    end
end

/// The ledger's lines: a heading, then each entry by date, description and
/// change, with amounts in `currency` written in `style`.
pub fn format_entries(currency: Currency, style: Style, entries: List<Entry>) -> List<String>
    (date, description, change) = Style.headings(style)
    heading = row(date, description, String.pad_end(change, 13))

    lines =
        entries
        |> Iter.sort_by(fn entry -> (entry.date, entry.description, entry.cents))
        |> Iter.map(&format_entry(currency, style, &1))

    [heading, ..lines]
end

fn format_entry(currency: Currency, style: Style, entry: Entry) -> String
    locale = Style.locale(style)
    date = Date.format_fields(entry.date, locale, DateFields"yMMdd")
    change = Money{amount: Int.to_decimal(entry.cents) / 100d, currency:}
    row(date, truncate(entry.description), format_change(change, style))
end

/// The table's three columns: a date ten wide, a description 25 wide, and
/// a change 13 wide, right-aligned. The heading pads its change on the
/// right first, so its title is left-aligned.
fn row(date: String, description: String, change: String) -> String
    [String.pad_end(date, 10), String.pad_end(description, 25), String.pad_start(change, 13)]
    |> String.join(" | ")
end

/// `description` cut to 22 characters and an ellipsis when it is wider than
/// its column.
fn truncate(description: String) -> String
    if String.length(description) <= 25 then
        description
    else
        String.take(description, 22) + "..."
    end
end

/// An amount as the style writes it. An amount not in parentheses ends with
/// a space, so the digits line up with the parenthesized ones.
fn format_change(change: Money, style: Style) -> String
    amount =
        Money.format(change, Style.locale(style), display: .Narrow, sign: Style.sign(style))
        |> String.replace("\u{a0}", " ")

    if String.ends_with(amount, ")") then
        amount
    else
        "${amount} "
    end
end

// FILE: ledger_test.nomi
import
    std::calendar.Date
    std::currency.Currency
    ledger.{self, Entry, Style}
end

test "ledger"
    cases: List<(String, Currency, Style, List<Entry>, List<String>)> = [
        (
            "empty ledger",
            Currency"USD",
            .American,
            [],
            [
                "Date       | Description               | Change       ",
            ],
        ),
        (
            "one entry",
            Currency"USD",
            .American,
            [
                {date: Date"2015-01-01", description: "Buy present", cents: -1000},
            ],
            [
                "Date       | Description               | Change       ",
                "01/01/2015 | Buy present               |      ($10.00)",
            ],
        ),
        (
            "credit and debit",
            Currency"USD",
            .American,
            [
                {date: Date"2015-01-02", description: "Get present", cents: 1000},
                {date: Date"2015-01-01", description: "Buy present", cents: -1000},
            ],
            [
                "Date       | Description               | Change       ",
                "01/01/2015 | Buy present               |      ($10.00)",
                "01/02/2015 | Get present               |       $10.00 ",
            ],
        ),
        (
            "multiple entries on same date ordered by description, as first written",
            Currency"USD",
            .American,
            [
                {date: Date"2015-01-02", description: "Get present", cents: 1000},
                {date: Date"2015-01-01", description: "Buy present", cents: -1000},
            ],
            [
                "Date       | Description               | Change       ",
                "01/01/2015 | Buy present               |      ($10.00)",
                "01/02/2015 | Get present               |       $10.00 ",
            ],
        ),
        (
            "final order tie breaker is change",
            Currency"USD",
            .American,
            [
                {date: Date"2015-01-01", description: "Something", cents: 0},
                {date: Date"2015-01-01", description: "Something", cents: -1},
                {date: Date"2015-01-01", description: "Something", cents: 1},
            ],
            [
                "Date       | Description               | Change       ",
                "01/01/2015 | Something                 |       ($0.01)",
                "01/01/2015 | Something                 |        $0.00 ",
                "01/01/2015 | Something                 |        $0.01 ",
            ],
        ),
        (
            "overlong description is truncated",
            Currency"USD",
            .American,
            [
                {
                    date:        Date"2015-01-01",
                    description: "Freude schoner Gotterfunken",
                    cents:       -123456,
                },
            ],
            [
                "Date       | Description               | Change       ",
                "01/01/2015 | Freude schoner Gotterf... |   ($1,234.56)",
            ],
        ),
        (
            "euros",
            Currency"EUR",
            .American,
            [
                {date: Date"2015-01-01", description: "Buy present", cents: -1000},
            ],
            [
                "Date       | Description               | Change       ",
                "01/01/2015 | Buy present               |      (€10.00)",
            ],
        ),
        (
            "Dutch locale",
            Currency"USD",
            .Dutch,
            [
                {date: Date"2015-03-12", description: "Buy present", cents: 123456},
            ],
            [
                "Datum      | Omschrijving              | Verandering  ",
                "12-03-2015 | Buy present               |   $ 1.234,56 ",
            ],
        ),
        (
            "Dutch locale and euros",
            Currency"EUR",
            .Dutch,
            [
                {date: Date"2015-03-12", description: "Buy present", cents: 123456},
            ],
            [
                "Datum      | Omschrijving              | Verandering  ",
                "12-03-2015 | Buy present               |   € 1.234,56 ",
            ],
        ),
        (
            "Dutch negative number with 3 digits before decimal point",
            Currency"USD",
            .Dutch,
            [
                {date: Date"2015-03-12", description: "Buy present", cents: -12345},
            ],
            [
                "Datum      | Omschrijving              | Verandering  ",
                "12-03-2015 | Buy present               |    $ -123,45 ",
            ],
        ),
        (
            "American negative number with 3 digits before decimal point",
            Currency"USD",
            .American,
            [
                {date: Date"2015-03-12", description: "Buy present", cents: -12345},
            ],
            [
                "Date       | Description               | Change       ",
                "03/12/2015 | Buy present               |     ($123.45)",
            ],
        ),
        (
            "multiple entries on same date ordered by description",
            Currency"USD",
            .American,
            [
                {date: Date"2015-01-01", description: "Get present", cents: 1000},
                {date: Date"2015-01-01", description: "Buy present", cents: -1000},
            ],
            [
                "Date       | Description               | Change       ",
                "01/01/2015 | Buy present               |      ($10.00)",
                "01/01/2015 | Get present               |       $10.00 ",
            ],
        ),
    ]

    subtests cases, (description, currency, style, entries, expected), description
        assert ledger.format_entries(currency, style, entries) == expected
    end
end
  • The exercise is a refactoring one: tracks ship a badly written printer to clean up. There is no Nomi stub to start from, so this is the solution written directly, against the canonical cases.
  • The canonical locale input, en_US or nl_NL, is a Style enum, American or Dutch, since the ledger has headings for those two and no others. Each style knows its std Locale and its three headings.
  • Dates and amounts come from std’s CLDR data rather than hand-written patterns. Date.format_fields with the skeleton yMMdd writes 01/01/2015 in en-US and 12-03-2015 in nl-NL, and Money.format with the Narrow symbol writes $1,234.56 and $ 1.234,56 (US dollars are US$ in Dutch with the plain symbol).
  • An American negative amount is in parentheses, ($10.00), which is CLDR’s accounting pattern for en: Money.format with sign: .Accounting writes it, and Style.sign picks it for American style only, since the canonical Dutch lines write $ -123,45.
  • One thing is the ledger’s own and is done by hand: the Dutch amount’s no-break space after the symbol becomes a plain space, which the canonical lines use.
  • An entry holds its change in cents, as the canonical input does, and the currency is the ledger’s. The change becomes a Money only to be formatted.
  • The entries are sorted by one tuple key, (date, description, cents) (style §37).
  • A row is its three columns padded and joined with " | ". The heading pads its last title on the right before the row pads it on the left, so the title sits at the left of its column and the amounts at the right.
  • The twelve canonical cases are one subtests table. Two canonical cases share the description “multiple entries on same date ordered by description”; the first of them, whose entries are on different dates, is named ”…, as first written” so each row has its own name.