In the Scripting breakout room of Discovery Summit 2024 we just discussed if there is a JSL function to replace the head of an expression.
Something like
Replace Head(myExpression, Expr(original head()), Expr(new head()));
to convert
original head(args)
into
new head(args)
In this context, one might think of Substitute. Besides replacing strings
Substitute ("hello", "h", "J", "l", "f", "o", "")
one can use Substitute also to replace Expressions, like in
Substitute({1+2},Expr(add()),Expr(subtract()))
It gets close, but it is far from optimal, e.g.
Substitute({1,2,{3,4}}, Expr(List()),Expr(Show()));
will return Show( 1, 2, Show( 3, 4 ) )
: (
A possible solution: convert the expression to a string and use Regex, then convert back.
this hurts when you know the magic of Expression handling : )
The best solution up to now - via expression handling:
Instead of replacing the head, extract all the arguments and insert them into the new head.
var = {1,2,{3,4}};
MyExpr = Expr(Show());
for(i=1, i<=NArg(var), i++,
InsertInto(MyExpr, Arg(var, i))
);
NameExpr(MyExpr);