Processing Flexible Arguments in Mathematica Functions

This is a branch and extension: Is it possible to disable Pattern :: patv?

Many Mathematica built-in functions allow for flexible arguments. In custom functions, I used Alternatives for this purpose, but comments and answers to the question mentioned indicate that this is at least non-standard and possibly undesirable.

Let me define the dummy function foo as an example.

 Off[Pattern::patv] p = {_?NumericQ, _?NumericQ}; foo[ {x : p ..} | x : p, {y__} | y__, ops : OptionsPattern[] ] /; Max[y] <= 10 := bar[#, y, ops] & /@ {x} 

foo accepts, in order:

  • matching patten p or a list of such objects.
  • a set of implicitly numerical objects with a maximum value of 10, either as a list or a sequence of arguments (since these entries themselves can be numerical lists with a maximum value of 10)
  • parameters matching OptionsPattern[]

If any of these conditions are not met, foo[args] returned invaluable.

Two patterns using Alternatives ( | ) are the most common cases, but they are not exceptional.

I'm struggling to figure out how best to use foo .

  • What is the canonical way to achieve this?

  • What are its advantages over using Alternatives ?

  • Is it easy to read?

+6
source share
1 answer

I believe that there are three canonical ways to solve flexible arguments:

  • everything goes: f[x_] ,
  • several forms: f[{x : p ..}] and f[x:p] , where one calls the other, and
  • alternation: f[{x : p ..} | x : p] f[{x : p ..} | x : p] .

The main difference is that you are dealing with the additional complexity of flexible arguments. Everyone can have their own advantages.

The main advantage of something is the simplicity of creating acceptable templates, but this leaves processing internal functions, which increases its complexity. For a good example, see ErrorBarPlots .m . Ultimately, ErrorListPlot relies on the second method, hidden behind the facade of the first method.

A method with multiple forms imposes complexity on the dispatcher when choosing the right alternative. It has the simplest functional form, since one form usually calls another form with the "correct" data layout. The difficulty with this method lies in the exponential growth of the specifications of functions with the number of parameters with alternatives. This can be limited by adopting a hybrid approach, such as that found in ErrorListPlot .

Alternation has the most complex form of the template and may require special processing to extract alternatives similar to anything. In addition, the templates themselves can be more difficult to build, and because of the possibility of additional processing, this method should be used the least often of the three. However, in some cases, as in your code, this method may be the simplest implementation.

+4
source

Source: https://habr.com/ru/post/903844/


All Articles