# Define function that behaves almost identically to Mathematica function

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}]


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.

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

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]


• OptionsPattern[ListPlot] is more precise. – Edmund Feb 20 at 23:06

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