I am writing a function that will take an expression as input. I want to make sure the expression is valid first before processing it. Looking for a correct to use MatchQ
(or if you have better method) to use which will return True
or False
when given the expression.
Specifications
The expression will have the following form
a1 Cos[x+b1] + a2 Cos[x+b2] + a3 Cos[x+b3] + ....
OR
a1 Sin[x+b1] + a2 Sin[x+b2] + a3 Sin[x+b3] + ....
So if you can parse one, then with some trick, can use the same parser with the other using OR
.
There can one or more terms there. Also, the amplitudes (the $a_i$) can be there or not there. Also, there is no need to check what is used for argument to the trig functions. So if expression is Cos[Cos[x]]
then that is ok, only FIRST level needs to be validated. The expression will be passed by TrigReduce[]
before. Your parser only needs to check for the above top level form.
Hence the following are all valid expression and should return True
Sin[x]
a Sin[x]
a Sin[x] + Sin[x +b]
Sin[x] + Sin[x + b] + c Sin[x]
These are NOT valid:
Sin[x] + Cos[x] (*mixed*)
a + Sin[x] (*first term has no sin nor cos *)
Sin[x]+ b + Sin[x + v]
So the function needed will have this specification
parse[expr_]
and will return either True
or False
.
What is the most efficient way to do this?
Test suite
To help you in making the parser, here are few expressions that should return True
and another set that should return False
ClearAll[x, a1, b1, a2, b2, a3, b3];
trueTests = {
3 Cos[x],
a1 Cos[x + b1],
Cos[x] + a1 Cos[x + b1],
a1 Cos[x] + a1 Cos[x + b1] + a2 Cos[x + b2],
3 Sin[x],
a1 Sin[x + b1],
Sin[x] + a1 Sin[x + b1],
a1 Sin[x] + a1 Sin[x + b1] + a2 Sin[x + b2]
}
falseTests = {
a1,
a1 Cos[x + b1] + Sin[x],
Cos[x] + b1,
a1 Cos[x] + a1 Cos[x + b1] + a2 Sin[x + b2],
Cos[x] + Sin[x]
}
MatchQ[{2 Sin[x], 4 Sin[2 x], Cos[x]}, {(_. (h : (Sin | Cos))[_. x + _.]) ..}]
should work $\endgroup$