6
$\begingroup$

I was trying to write my own plot function taking as unit size cm instead of points. I've tried

Options[MyPlot] = Options[Plot];
SetOptions[MyPlot, ImageSize -> {8.22, 5.03}];
MyPlot[fun_, int_, opts_: OptionsPattern[]] := {fun, int, 
  ImageSize -> OptionValue[MyPlot, opts, ImageSize]*72/2.54};
Plot @@ MyPlot[Sin[2 \[Pi] x], {x, 0, 1}, ImageSize -> 10]

and with

Options[MyGraphics] = Options[Graphics];
SetOptions[MyGraphics, ImageSize -> {8.22, 5.03}];
MyGraphics[prims_, opts_: OptionsPattern[]] := {prims, 
  ImageSize -> OptionValue[MyGraphics, opts, ImageSize]*72/2.54};
Graphics@@MyGraphics[Rectangle[]]

the error: OptionValue::rep: "OptionsPattern[] is not a valid replacement rule." came out.

Where am I wrong? It seems I am a bit confusing on the way to use OptionsPattern[] and using _ or __ in the function arguments before the opts.

Thanks!

$\endgroup$

1 Answer 1

15
$\begingroup$

You must use opts : OptionsPattern[] and not opts_ : OptionsPattern[].

The : character has a double role: it can indicate a pattern name or an optional argument. If the left-hand-side is a symbol then it indicates a pattern name, otherwise it indicates an optional argument.

Examples:

a_ is a Blank named a.

a : _ is a blank named a using : syntax.

a_ : x is a blank named a as optional argument with default value x.

_ : x is an unnamed optional blank with default value x (I'm not sure if this has any use at all).

a : _ : x is a blank named a as optional argument with default value x.

$\endgroup$
4
  • $\begingroup$ The x: _ : x pattern isn't unnamed: it's a Blank pattern with name x and default value x. Try: f[x : _ : x] := x, then f[] returns x and f[1] returns 1. The case x: a : _ : x is also misinterpreted (but more complicated). $\endgroup$ Commented May 1, 2016 at 15:54
  • $\begingroup$ The pattern x : a : _ : x means "the pattern a named x with default value _ : x": try Clear[f, a, x]; f[x : a : _ : x] := x, then f[] returns the default value _ : x, f[a] returns a and f[1] returns unevaluated because 1 doesn't match the pattern a. $\endgroup$ Commented May 1, 2016 at 16:02
  • $\begingroup$ @AlexeyPopkov I wrote it in a confusing way, so you thought that some colons that were just punctuation in the text were actually code. I rewrote it to avoid confusion: I put the code at the beginning of each line. $\endgroup$
    – Szabolcs
    Commented May 1, 2016 at 16:19
  • $\begingroup$ (+1) Now it is clear. I'll keep my comments since despite they don't correspond to the answer anymore they still can have some educational value. $\endgroup$ Commented May 1, 2016 at 16:28

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.