Skip to content

Conversation

@Lorenzobattistela
Copy link
Contributor

@Lorenzobattistela Lorenzobattistela commented Aug 4, 2025

The superposition collapse algorithm is responsible for handling
superposed values (marked with
SUP nodes) in the computation tree. When a computation contains
superpositions, the algorithm
must eventually "collapse" them.

In the `examples/enum_primes` example, the program generates a
superposition that produces two possible
results: λa ((a 853) 947) and λa ((a 947) 853). These are lambda
functions that, when given an
argument a, apply it to two numbers in different orders.

The bug was that the new collapse algorithm was producing just 947 and
853 - raw numbers without
the lambda wrapper or application structure. This happened because the
algorithm was collapsing
superpositions too eagerly during the initial tree traversal.

The new algorithm uses a sophisticated type-safe builder pattern that
processes terms
recursively. When it encountered a superposition (CSup), it would
immediately apply a "collapse
selection" mechanism (CCol) that forces branch selection based on
context. This works perfectly
for nested superpositions that need to be resolved based on their
surrounding context.

However, for top-level superpositions (those that should remain in the
final result), this eager
collapse was incorrect. The algorithm was destroying the lambda and
application structure that
wrapped the superposed values, leaving only the bare numeric values.

The fix identifies when we're processing top-level terms (when the tms
list is empty) and handles
  them differently:

1. For top-level superpositions (CSup): Instead of using the
context-dependent collapse
mechanism, preserve the superposition structure and process each branch
independently
2. For top-level lambdas (CLam): Process the lambda body independently
to preserve its internal
structure
3. For top-level applications (CApp): Process the function and argument
independently to maintain
  the application structure

This preserves the complete term structure for top-level expressions
while still using the
optimized collapse mechanism for nested superpositions where
context-dependent resolution is
correct.

The key insight is distinguishing between:
- Nested superpositions: Should be collapsed based on surrounding
context (original behavior)
- Top-level superpositions: Should be preserved for the final flattening
step (fixed behavior)
@VictorTaelin VictorTaelin merged commit b56f5f0 into main Aug 21, 2025
2 checks passed
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.

3 participants