SymbolicUtils.jl
SymbolicUtils.jl copied to clipboard
Pattern Matching with subtraction is seemingly broken
julia> @acrule(-1 - ~x => "match")(-1 - x)
julia> @rule(-1 - ~x => "match")(-1 - x)
ref https://julialang.zulipchat.com/#narrow/stream/274208-helpdesk-(published)/topic/Symbolics.2Ejl.20derivative.20cot(x)
note
julia> @rule(-1 + (-1)*cot(~x)^2 => "works!")(-1 - cot(x)^2)
"works!"
in case that makes it clearer what's going on
https://github.com/JuliaSymbolics/SymbolicUtils.jl/issues/256 may alleviate some of the confusion here.
I'm thinking of adding a variant of @rule
called @numrule
which sets up the LHS in the right way to be able to match this.
Bear in mind that I'm quite ignorant of how this is actually doing the pattern matching under the hood, so I may be thinking about this quite wrongly; but naively, I don't think it's such a good idea to have lots of different variations of @rule
which users then have to distinguish between (I'm not talking about @acrule
here, it's more clear when to use that). I expect it'll be really hard for someone not intimately familiar with the pattern matching to ascertain which rule should be used. It would seem to me that the user facing pattern matching would have to handle these cases, or it might become too difficult to use.
Under the hood they "compile" a function to do the pattern matching, they do it with a lot of higher order functions fu. So there are just a few ways to do this in a razonable manner.
One is to convert the Symbolic
expression into a different representation and then do the pattern matching. But the convertion would happen every time you want to match, becomming (probably) time expensive (unless catched, but this would cause more memory use).
Other way is to modify the expression before the actual rule is compiled, this needs to be done in the macro. Digging here you would need to add an @numrule
so the LHS expression match the representations of Symbolic{<:Number}
with the structures Add
, Mul
and Pow
(Term
is well behabed).
But I concur with you in that adding a @numrule
feels a little weird, as it would expose the user in some sence to the internal representation of SymbolicUtils.
Ufff, this goes further... found this while fixing #208.
julia> using SymbolicUtils
julia> @syms x y z
(x, y, z)
julia> @rule(~x-1 => ~x)(x-1) # expected to nothing
julia> @rule(~x+(-1) => ~x)(x-1) # not so expected
julia> @numrule(~x-1 => ~x)(x-1) # maybe expected to work
julia> @numrule(~x+(-1) => ~x)(x-1) # what???
~My supected violator is the pattern matching machinery. I'll look at this one I finish the current problem causing #208.~
Nevermind, the problem is that @rule
and @numrule
doesn't reorder their terms... so @numrule(~x-1)
does work, the problem is that argument(x-1)
is [-1, x]
.
I think, I can change this order for @numrule
so the literals go where they need to be (and reduce?), I'l do this after the current change commented at #208.