Message Boards Message Boards

0
|
3337 Views
|
6 Replies
|
4 Total Likes
View groups...
Share
Share this post:

Pattern matching: BlankSequence in combination with Flat attribute

Posted 3 years ago

Dear all,

regardless of the sense of the following definitions:

f[x_ + y_Plus] := {x, {y}}
g[x_ + y__Plus] := {x, {y}}

Why does g not match the following expression, as it does with f:

f[a + b + c]
g[a + b + c]

Result:

{a, {b + c}}
g[a + b + c]

I would expect, g[a+b+c] is transformed to g[a + Plus(b,c)] (due to the Flat attribute of Plus) and then a matches x_ and Plus(b,c) matches y__ Plus, even because y__ Plus is less specific than y_ Plus (in case of f)

POSTED BY: Martin Guttmann
6 Replies
POSTED BY: Martin Guttmann

also, when matching flat functions, it is often useful to use Shortest and Longest. For example:

In[7]:= foo[aa, bb, cc,  dd] /. (foo[Longest[x_], foo[y__]] -> zz[{x, y}])

Out[7]= zz[{foo[aa, bb, cc], dd}]

Regards

POSTED BY: Neil Singer
POSTED BY: Neil Singer

It is clear, that BlackSequence matches a sequence, but also one element is a sequence, as it is working here:

h[x_ + y__Times] := {x, {y}}
h[a + b*c]

which gives

{a, {b c}}
POSTED BY: Martin Guttmann

Martin,

The difference is that x_ matches an expression while y__ matches a sequence. So for example, this will work:

g[x_ + Plus[y__]] := {x, {y}}

Also using Shortest and Longest helps in matching sequences.

Regards,

Neil

POSTED BY: Neil Singer
Posted 3 years ago

Martin:

Thanks for the great question.

I'm surprised that f[] matches.

FullForm[a + b + c] is Plus[a, b, c].

Of course this is equivalent to a + Plus[b, c], but I don't understand why Mathematica would have transformed Plus[a, b, c] to a + Plus[b, c] and not Plus[a, b] + c.

I'm hoping someone chimes in on this one.

POSTED BY: Mike Besso
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract