Skip to content

Commit

Permalink
POC #972 FullDefiniton better recursive collecting unprotected symbols
Browse files Browse the repository at this point in the history
  • Loading branch information
axkr committed Apr 30, 2024
1 parent 6b86bde commit 8ab7269
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -276,13 +276,9 @@ public IAST definition() {
@Override
public IAST fullDefinition() {
Set<ISymbol> symbolSet = new HashSet<ISymbol>();
IAST rules = definition();
for (int i = 1; i < rules.size(); i++) {
IExpr rule = rules.get(i);
collectSymbolsRecursive(rule, symbolSet, x -> x.isSymbol() && !(x.isProtected()));
}
collectSymbolsRecursive(this, symbolSet, x -> x.isSymbol() && !(x.isProtected()));
if (symbolSet.size() > 0) {
IASTAppendable fullDefinition = F.ListAlloc(rules.size() + symbolSet.size());
IASTAppendable fullDefinition = F.ListAlloc();
Iterator<ISymbol> iterator = symbolSet.iterator();
while (iterator.hasNext()) {
ISymbol symbol = iterator.next();
Expand All @@ -299,26 +295,43 @@ public IAST fullDefinition() {
return F.NIL;
}

private static void collectSymbolsRecursive(ISymbol symbol, Set<ISymbol> symbolSet,
Predicate<ISymbol> predicate) {
final IAST rules = symbol.definition();
for (int i = 1; i < rules.size(); i++) {
IExpr rule = rules.get(i);
collectSymbolsRecursive(rule, symbolSet, predicate);
}
}

private static void collectSymbolsRecursive(IExpr expr, Set<ISymbol> symbolSet,
Predicate<ISymbol> predicate) {
if (expr.isAST()) {
IAST list = (IAST) expr;
IExpr head = expr.head();
if (head.isSymbol()) {
if (predicate.test((ISymbol) head)) {
symbolSet.add((ISymbol) head);
final ISymbol symbol = (ISymbol) head;
if (predicate.test(symbol)) {
if (!symbolSet.contains(symbol)) {
symbolSet.add(symbol);
collectSymbolsRecursive(symbol, symbolSet, predicate);
}
}
} else {
collectSymbolsRecursive(head, symbolSet, x -> x.isSymbol());
collectSymbolsRecursive(head, symbolSet, predicate);
}
for (int i = 1; i < list.size(); i++) {
IExpr arg = list.getRule(i);
collectSymbolsRecursive(arg, symbolSet, predicate);
}
} else {
if (expr.isSymbol()) {
if (predicate.test((ISymbol) expr)) {
symbolSet.add((ISymbol) expr);
final ISymbol symbol = (ISymbol) expr;
if (predicate.test(symbol)) {
if (!symbolSet.contains(symbol)) {
symbolSet.add(symbol);
collectSymbolsRecursive(symbol, symbolSet, predicate);
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ public void testSave() {
check("temp = FileNameJoin({$TemporaryDirectory, \"saved.txt\"});Print(temp);", //
"");
check("g(x_) := x^3;"//
+ "g(x_,y_) := f(x,y);"//
+ "SetAttributes(f, Listable);"//
+ "f(x_) := g(x^2);", //
"");
Expand Down

0 comments on commit 8ab7269

Please sign in to comment.