Skip to content

Add match-count builtin: count matches without materializing results#166

Closed
Tsion-Teklay wants to merge 1 commit intotrueagi-io:mainfrom
Tsion-Teklay:main
Closed

Add match-count builtin: count matches without materializing results#166
Tsion-Teklay wants to merge 1 commit intotrueagi-io:mainfrom
Tsion-Teklay:main

Conversation

@Tsion-Teklay
Copy link
Copy Markdown

Summary

This PR adds a match-count builtin that efficiently counts the number of atoms matching a pattern without materializing the entire result set. It addresses a critical performance issue where counting matches using (length (collapse (match ...))) would cause stack overflow on large knowledge bases.

Problem

Counting how many atoms in a space match a pattern is currently done via (length (collapse (match ))), which builds a Prolog list of every match. On large in-RAM AtomSpaces this exhausts the stack long before the count is needed — the caller only wants a number, not the results themselves.

Solution

Implemented match-count using aggregate_all/3 which is failure-driven and keeps a single counter — no list is built. The new function:

  • Uses constant memory regardless of result size
  • Reuses the existing match/4 implementation
  • Returns the count directly without materializing matches

Implementation

match-count(Space, Pattern, Count) :-  
    aggregate_all(count, match(Space, Pattern, _, _), Count).

The function is added to src/spaces.pl and registered in src/metta.pl to enable MeTTa calls.

Testing

Added comprehensive tests in examples/match_count.metta covering:

Full pattern count: (match-count &self (parent $p $c)) => 5
Bound pattern count: (match-count &self (parent alice $c)) => 2
Zero matches: (match-count &self (parent zelda $c)) => 0

Test with:
sh run.sh ./examples/match_count.metta

Expect: three lines each ending in ✅

Files changed

src/spaces.pl — defines match-count/3 as a wrapper over aggregate_all(count, match(...), Count)
src/metta.pl — registers match-count in the function list
examples/match_count.metta — three test cases

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant