Skip to main content
3 of 4
replaced http://mathematica.stackexchange.com/ with https://mathematica.stackexchange.com/

How to Set Priority Between Longest and Shortest

As is shown in this post's answer, it seems that though you can set priority of Longest (or Shortest) by Longest[patt,prio], There's no direct way (at least no direct way as far as I know) to set priority between them.

It means that the priority setting with Shortest will just define the priority between multiple Shortests but leave Longest uninfluenced. But I suppose there must be some cases when we need to specify the priority between them, for example, we need pattern1 to be shortest, after that, we need to make pattern2 longest, then we need to make pattern3 shortest.

How can we do this? Any help will be appreciated, thanks!!!

I'll update if I can find any proper example of this.


#Update 1

I'll have to admit though I think this problem as quite prevailing, it's quite hard to find an example in a few days. But here is one:

Replace[{1, 2}, {Longest[Shortest[x__]], y___} :> {x}]

(*{1}*)

Replace[{1, 2}, {Shortest[Longest[x__]], y___} :> {x}]

(*{1,2}*)

It seems that when Longest and Shortest compete with each other in this simple case, it will put inner level at a higher priority. But if I want to use the first code while getting the second result, the most natural way is to add a priority to it. However, the following code will not work.

Replace[{1, 2}, {Longest[Shortest[x__, 1], 2], y___} :> {x}]

(*{1}*)

Just as I've said before, Longest and Shortest have their own priority, so this method will not work.

When meeting with similar question when two Longest or two Shortest compete with each other, we can usually solve them by adding a priority:

Replace[{1, 2, 3, 4}, {Longest[x__, 1], Longest[y__, 2]} :> {{x}, {y}}]

I'm just wondering how can we do the same when there's conflict between Longest and Shortest.

Wjx
  • 9.7k
  • 1
  • 34
  • 70