Functional Weave
Code in Rust

finance.bank-reconcile-match

Match bank statement lines to ledger entries by exact amount, a date window and reference similarity, deterministically.

1.0.0 · published 2026-10-03 by charlie · Anterra

Pinned by 19 tests, run in TypeScript, Python and Rust.

What it does

The auto-match step of a bank reconciliation: pair each bank statement line with at most one cash-book entry, and list what is left on each side for a person to deal with.

**A pair is a candidate** when the amounts are exactly equal (same currency, same sign, same minor units), the dates are at most `dateWindowDays` apart in either direction, and the references are at least `minSimilarity` alike.

For example

  • match_bank_lines(bank lines ×3, ledger entries ×3, 3, 0) → matches ×2, unmatched bank B3, unmatched ledger L3 a receipt and a direct debit match; the stray line on each side is left over
  • match_bank_lines(bank lines ×2, ledger entries ×2, 3, 0) → matches ×2, unmatched bank , unmatched ledger two equal payments pair by reference, not by the order the ledger lists them
  • match_bank_lines(bank lines ×2, ledger entries ×2, 3, 0) → matches ×2, unmatched bank , unmatched ledger the best pair overall is taken first, even when it is not the first bank line's nearest date

The function

The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.

pub fn match_bank_lines(bank_lines: &[ReconcileLine], ledger_entries: &[ReconcileLine], date_window_days: i64, min_similarity: i64) -> Reconciliation
bank_linesReconcileLine[]lines from the bank statement
ledger_entriesReconcileLine[]unreconciled entries in the cash book
date_window_daysinthow many days apart a bank line and a ledger entry may be dated, 0 or more
min_similarityintthe least reference similarity a match needs, 0 to 10000; 0 matches on amount and date alone
returnsReconciliation

The types it declares, generated into your project

/// A bank line or a ledger entry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReconcileLine {
    /// unique within its list
    pub id: String,
    pub date: String,
    /// positive for money in, negative for money out, on both sides
    pub amount: Money,
    pub reference: String,
}

/// One bank line paired with one ledger entry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReconcileMatch {
    pub bank_id: String,
    pub ledger_id: String,
    /// bank date less ledger date, in days
    pub day_difference: i64,
    /// reference similarity, 0 to 10000
    pub similarity: i64,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Reconciliation {
    /// in bank-line order
    pub matches: Vec<ReconcileMatch>,
    /// ids, in input order
    pub unmatched_bank: Vec<String>,
    /// ids, in input order
    pub unmatched_ledger: Vec<String>,
}

Your code names it in one line, in the file that uses it

fune!(finance.bank-reconcile-match@^1);  // then call match_bank_lines(…)
impl/rust.rs · 167 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::dates_days_between::days_between;  ← from dates.days-between ^1.0.0 · built alongside by fune
use super::math_round_div::round_div;  ← from math.round-div ^1.0.0 · built alongside by fune
use super::money_amount::money_from_value;  ← from money.amount ^1.0.0 · built alongside by fune

fn reduce(reference: &str) -> Vec<u8> {
    reference
        .bytes()
        .filter(|b| b.is_ascii_alphanumeric())
        .map(|b| b.to_ascii_uppercase())
        .collect()
}

/// Sørensen-Dice on adjacent character pairs, 0 to 10000, rounded down.
fn similarity(a: &str, b: &str) -> i64 {
    let x = reduce(a);
    let y = reduce(b);
    if !x.is_empty() && x == y {
        return 10000;
    }
    let left: Vec<&[u8]> = x.windows(2).collect();
    let right: Vec<&[u8]> = y.windows(2).collect();
    if left.is_empty() || right.is_empty() {
        return 0;
    }
    let mut used = vec![false; right.len()];
    let mut shared: i64 = 0;
    for pair in &left {
        if let Some(at) = (0..right.len()).find(|&i| !used[i] && right[i] == *pair) {
            used[at] = true;
            shared += 1;
        }
    }
    round_div(2 * shared * 10000, (left.len() + right.len()) as i64, "down")
}

fn check_ids(lines: &[ReconcileLine], side: &str) {
    for (i, line) in lines.iter().enumerate() {
        if lines[..i].iter().any(|other| other.id == line.id) {
            panic!("duplicate {} id \"{}\"", side, line.id);
        }
    }
}

/// Pair bank lines with ledger entries: equal amount, dates within the window,
/// references alike enough, best pairs first and ties broken by input order.
///
/// # Panics
/// Panics on a negative window, a similarity outside 0..=10000, duplicate ids
/// or malformed dates.
pub fn match_bank_lines(
    bank_lines: &[ReconcileLine],
    ledger_entries: &[ReconcileLine],
    date_window_days: i64,
    min_similarity: i64,
) -> Reconciliation {
    if date_window_days < 0 {
        panic!("dateWindowDays must be 0 or more, received {}", date_window_days);
    }
    if !(0..=10000).contains(&min_similarity) {
        panic!("minSimilarity must be 0 to 10000, received {}", min_similarity);
    }
    check_ids(bank_lines, "bank line");
    check_ids(ledger_entries, "ledger entry");

    // (score, days, bank index, ledger index)
    let mut candidates: Vec<(i64, i64, usize, usize)> = Vec::new();
    for (b, bank) in bank_lines.iter().enumerate() {
        for (l, entry) in ledger_entries.iter().enumerate() {
            let days = days_between(&entry.date, &bank.date);
            if bank.amount.currency != entry.amount.currency || bank.amount.minor != entry.amount.minor {
                continue;
            }
            if days.abs() > date_window_days {
                continue;
            }
            let score = similarity(&bank.reference, &entry.reference);
            if score < min_similarity {
                continue;
            }
            candidates.push((score, days, b, l));
        }
    }
    candidates.sort_by(|p, q| {
        q.0.cmp(&p.0)
            .then(p.1.abs().cmp(&q.1.abs()))
            .then(p.2.cmp(&q.2))
            .then(p.3.cmp(&q.3))
    });

    let mut bank_match: Vec<Option<ReconcileMatch>> = vec![None; bank_lines.len()];
    let mut ledger_used = vec![false; ledger_entries.len()];
    for (score, days, b, l) in candidates {
        if bank_match[b].is_some() || ledger_used[l] {
            continue;
        }
        bank_match[b] = Some(ReconcileMatch {
            bank_id: bank_lines[b].id.clone(),
            ledger_id: ledger_entries[l].id.clone(),
            day_difference: days,
            similarity: score,
        });
        ledger_used[l] = true;
    }

    let mut matches = Vec::new();
    let mut unmatched_bank = Vec::new();
    for (b, found) in bank_match.into_iter().enumerate() {
        match found {
            Some(m) => matches.push(m),
            None => unmatched_bank.push(bank_lines[b].id.clone()),
        }
    }
    let unmatched_ledger = ledger_entries
        .iter()
        .enumerate()
        .filter(|(l, _)| !ledger_used[*l])
        .map(|(_, e)| e.id.clone())
        .collect();
    Reconciliation {
        matches,
        unmatched_bank,
        unmatched_ledger,
    }
}

pub fn reconcile_line_from_value(v: &Value) -> ReconcileLine {
    ReconcileLine {
        id: v.get("id").as_str().to_string(),
        date: v.get("date").as_str().to_string(),
        amount: money_from_value(v.get("amount")),
        reference: v.get("reference").as_str().to_string(),
    }
}

fn strings(items: &[String]) -> Value {
    Value::Arr(items.iter().map(|s| Value::str(s)).collect())
}

pub fn reconciliation_to_value(r: &Reconciliation) -> Value {
    Value::obj(vec![
        (
            "matches",
            Value::Arr(
                r.matches
                    .iter()
                    .map(|m| {
                        Value::obj(vec![
                            ("bankId", Value::str(&m.bank_id)),
                            ("ledgerId", Value::str(&m.ledger_id)),
                            ("dayDifference", Value::Int(m.day_difference)),
                            ("similarity", Value::Int(m.similarity)),
                        ])
                    })
                    .collect(),
            ),
        ),
        ("unmatchedBank", strings(&r.unmatched_bank)),
        ("unmatchedLedger", strings(&r.unmatched_ledger)),
    ])
}

pub fn fune_vector(args: &[Value]) -> Value {
    let bank: Vec<ReconcileLine> = args[0].as_arr().iter().map(reconcile_line_from_value).collect();
    let ledger: Vec<ReconcileLine> = args[1].as_arr().iter().map(reconcile_line_from_value).collect();
    reconciliation_to_value(&match_bank_lines(&bank, &ledger, args[2].as_i64(), args[3].as_i64()))
}

Install

fune build

With that line in your source, in a Rust project (language rust in fune.project), fune build resolves it and its 3 dependencies, pins them in fune.lock, downloads only the Rust package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. A crate’s build.rs runs it before every compile. Or pin a range in fune.project and build in one step:

fune add finance.bank-reconcile-match
Download for Rust finance.bank-reconcile-match-1.0.0-rust.fune · 21,091 bytes sha256 874c7f4c4c107fc502c48b838791d9e960c786d6293b508d9163cbd9ad05b9af

The manifest, vectors and README with only the Rust implementation. Install it without the registry with fune add ./finance.bank-reconcile-match-1.0.0-rust.fune, or fetch it from a terminal with fune pull finance.bank-reconcile-match@1.0.0:rust.

The whole function, every language, is one file too: finance.bank-reconcile-match-1.0.0.fune, 28,900 bytes, sha256 fb3977c3dbadd7f9c05039af4e56d6ec222201493cb059430c7cf27c85a4a88b. It installs into a project of any language.

Customise it in your app

The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.

before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.

// fune: before finance.bank-reconcile-match

after — your function gets the result and the arguments, and returns the final result.

// fune: after finance.bank-reconcile-match

replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.

// fune: replace dates.days-between in finance.bank-reconcile-match
// fune: replace math.round-div in finance.bank-reconcile-match
// fune: replace money.amount in finance.bank-reconcile-match

step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show finance.bank-reconcile-match --steps.

// fune: step finance.bank-reconcile-match after <n|label>

Tests

A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.

CaseArgumentsExpected
a receipt and a direct debit match; the stray line on each side is left over bank lines ×3, ledger entries ×3, 3, 0 → matches ×2, unmatched bank B3, unmatched ledger L3
two equal payments pair by reference, not by the order the ledger lists them bank lines ×2, ledger entries ×2, 3, 0 → matches ×2, unmatched bank , unmatched ledger
the best pair overall is taken first, even when it is not the first bank line's nearest date bank lines ×2, ledger entries ×2, 3, 0 → matches ×2, unmatched bank , unmatched ledger
equal similarity: the nearer date wins bank lines ×1, ledger entries ×2, 3, 0 → matches ×1, unmatched bank , unmatched ledger L1
a complete tie goes to the earlier ledger entry bank lines ×1, ledger entries ×2, 3, 0 → matches ×1, unmatched bank , unmatched ledger L2
the date window is inclusive: 3 days matches, 4 does not bank lines ×2, ledger entries ×2, 3, 0 → matches ×1, unmatched bank B2, unmatched ledger L2
a zero window needs the same date bank lines ×1, ledger entries ×1, 0, 0 → matches , unmatched bank B1, unmatched ledger L1
a reference below the minimum similarity does not match bank lines ×1, ledger entries ×1, 3, 5,000 → matches , unmatched bank B1, unmatched ledger L1
similarity counts repeated pairs once each: AAAA against AA is 5000 bank lines ×1, ledger entries ×1, 3, 5,000 → matches ×1, unmatched bank , unmatched ledger
ACME LTD against ACME is 6666, rounded down bank lines ×1, ledger entries ×1, 3, 0 → matches ×1, unmatched bank , unmatched ledger
Show the other 9 tests
CaseArgumentsExpected
INV1001 against INV1002 is 8333 bank lines ×1, ledger entries ×1, 3, 0 → matches ×1, unmatched bank , unmatched ledger
the same amount in another currency is not a match bank lines ×1, ledger entries ×1, 3, 0 → matches , unmatched bank B1, unmatched ledger L1
money out does not match money in bank lines ×1, ledger entries ×1, 3, 0 → matches , unmatched bank B1, unmatched ledger L1
nothing to match , , 3, 0 → matches , unmatched bank , unmatched ledger
a negative window is refused , , -1, 0 → error: dateWindowDays must be 0 or more
a similarity over 10000 is refused , , 3, 10,001 → error: minSimilarity must be 0 to 10000
duplicate bank ids are refused bank lines ×2, , 3, 0 → error: duplicate bank line id "B1"
duplicate ledger ids are refused , ledger entries ×2, 3, 0 → error: duplicate ledger entry id "L1"
an impossible date is refused bank lines ×1, ledger entries ×1, 3, 0 → error: not a real calendar date

More from the author

**Choosing among candidates** is where reconciliations go wrong, so it is fixed and global rather than first-come-first-served. All candidate pairs are ranked by, in order:

1. higher reference similarity, 2. fewer days apart, 3. earlier bank line (input order), 4. earlier ledger entry (input order),

and taken best first, skipping any pair whose bank line or ledger entry is already matched. Two payments of 500.00 on the same day, referenced INV2002 and INV2001, pair with the ledger entries of those references even when the ledger lists them the other way round; matching bank lines in order to the first equal amount would cross them. The same inputs always give the same pairs.

**Reference similarity** is a Sørensen-Dice score on character pairs, in basis points: both references are reduced to their ASCII letters and digits in upper case ("INV-1001 Acme" becomes "INV1001ACME"), and the score is twice the number of shared adjacent-character pairs over the total number of pairs, counting repeats, rounded down. Identical non-empty references score 10000; a reference with fewer than two characters after reduction scores 0 against anything else, as does an empty one. "INV1001" against "INV1001ACME" is 7500; against "INV1002" it is 8333.

Matches come back in bank-line order, with the day difference (bank date less ledger date; positive when the bank cleared later) and the similarity that justified them. Ids must be unique within each list. One-to-many matches (one deposit paying several invoices) are not attempted; they need a person or a separate rule.

Files

PathBytes
README.md2,010
impl/python.py3,722
impl/rust.rs5,638
impl/typescript.ts3,801
vectors.json8,275