10
$\begingroup$

Often I like to define my own functions that are almost exactly the same as Mathematica defined functions, apart from a few tweaks. See this question for example. I want to define them properly so they handle optional arguments correctly. What is a general strategy for accomplishing this? Here's a concrete (esoteric) example. I define myListPlot that is almost identical to ListPlot except that is adds a gridline corresponding to the first data point.

data = Table[RandomReal[], {x, 1, 10}]
myListPlot[data_, opts_] := ListPlot[data, GridLines -> {None, {data[[1]]}}, opts]
myListPlot[data, {PlotStyle -> Red, Joined -> True}]

The ListPlot generated by the above code

Not too bad. However I have to pass the optional arguments as a list. Instead, I would like to pass the optional arguments in the same way one does with ListPlot. In other words, I would like to modify myListPlot so that I would pass arguments like

myListPlot[data, PlotStyle -> Red, Joined -> True]

Perhaps I'm going about this completely the wrong way. Nevertheless I hope the reader understands what I'm trying to accomplish and can suggest a solution.

$\endgroup$
2
  • $\begingroup$ Try changing myListPlot[data_, opts_] to myListPlot[data_, opts___]. $\endgroup$
    – rafalc
    Commented Feb 20, 2019 at 14:50
  • $\begingroup$ Works like a charm. Why not go ahead and make it an answer. $\endgroup$
    – Tom
    Commented Feb 20, 2019 at 14:51

2 Answers 2

17
$\begingroup$

If you want to constrain it to only options from ListPlot, you could use OptionsPattern in combination with FilterRulesand Options.

myListPlot[data_, opts : OptionsPattern[]] := 
 ListPlot[data, GridLines -> {None, {data[[1]]}}, 
  FilterRules[{opts}, Options[ListPlot]]]

which results in:

myListPlot[data, PlotStyle -> Red, Joined -> True]

Mathematica graphics

$\endgroup$
1
  • $\begingroup$ OptionsPattern[ListPlot] is more precise. $\endgroup$
    – Edmund
    Commented Feb 20, 2019 at 23:06
9
$\begingroup$

The usual way to define a Wolfram Language function that takes n arguments and an arbitrary number of options is like this:

f[arg1_, ..., argn_, opts___] := ...

A little bit of pattern matching background (taken from the WL reference):

  • _ any single expression
  • x_ any single expression, to be named x
  • __ any sequence of one or more expressions
  • x__ sequence named x
  • x__h sequence of expressions, all of whose heads are h
  • ___ any sequence of zero or more expressions
  • x___ sequence of zero or more expressions named x
  • x___h sequence of zero or more expressions, all of whose heads are h
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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