0
$\begingroup$

I am trying to write the simplest (and efficient) pattern that matches the linear combination of all functions except when the combination produces zero?

Consider the following as an example:

pattern=HoldPattern[Except[0,(_:1)*Optional[Fibonacci[_],0]+(_:1)*Optional[LucasL[_],0]]];

Now if I use this to match the following cases:

MatchQ[pattern]/@{
    0,
    2 LucasL[n],
    Fibonacci[n],
    -(Fibonacci[n]/2)+LucasL[n]/2
}

I want the pattern to produce true for the last three, i.e. {False, True, True, True}.

How do I fix this pattern?

$\endgroup$
3
$\begingroup$

There is no Optional Head Pattern specification that I know of. In the OP pattern the Plus head is specified in the pattern so cases of individual terms are not matched.

I use Alternatives to construct a pattern for the terms, termPattern. Then use Alternatives with Repeated to allow for an individual term or a linear combination of the terms.

With

termPattern = (_ : 1) Optional[Fibonacci[_] | LucasL[_], 0];
pattern = Except[0, termPattern | HoldPattern[Plus][termPattern ..]];

Then

MatchQ[pattern]/@{
    0,
    2 LucasL[n],
    Fibonacci[n],
    -(Fibonacci[n]/2) + LucasL[n]/2
}
{False, True, True, True}

Also

MatchQ[pattern][
 a LucasL[n] + b Fibonacci[n] - (Fibonacci[n]/2) + LucasL[n]/2
 ]
True

Hope this helps.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.