Given list L:=[3,4,x,x^2,x^3]; return list of all exponents of x (other than 1). So result should be [2,3]
But this has to be done using patmatch, as this is what I am learning. Not using other means. This is my current code that does this.
restart;
L:=[3,4,x,x^2,x^3];
f:=proc(X::anything,x::symbol)
local la,n;
if patmatch(X,x^n::nonunit(anything),'la') then
assign(la);
RETURN(n);
else
RETURN(NULL);
fi;
end proc;
map(X->f(X,x),L);
Returns [2,3]
I wanted to shorten it using `if` so that no need to call external function f() as shown. So I wrote
L:=[3,4,x,x^2,x^3];
map(X->`if`( patmatch(X,x^n::anything,'la'),[assign(la), n],NULL),L);
But the problem is that on first entry, the assign(la) now assigns value to n and hence it is no longer a name for the next element in the list L. This gives error
Error, (in PatternMatching:-AlgStruct:-Match) first operand of `::' must be a name
So I added unassign('n') like this
restart;
L:=[3,4,x,x^2,x^3];
map(X->[unassign('n'),`if`( patmatch(X,x^n::nonunit(anything),'la'),[assign(la), n],NULL)][],L);
And now this returns
[[2], [3]]
How to make it return [2,3]? Why did it add extra []? How can the above be shortened more? and still return [2,3]
edit: I found how to get rid of the extra [], like this
restart;
L:=[3,4,x,x^2,x^3];
map(X->[unassign('n'),`if`( patmatch(X,x^n::nonunit(anything),'la'),[assign(la), n][],NULL)][],L);
Now it returns [2,3] , needed to add extra [] after each closing [.....]
In another system, the code is
Cases[{3, 4, x, x^2, x^3}, x^n_ -> n]
{2, 3}
I was trying to make the Maple code as short as possible. I know it will not be as short as the above.
The question is: Can above code be made shorter but still use patmatch?
Again, I am looking for only solution using patmatch. I know I can use select and types in Maple to do this also.
Maple 2024.2