I have function the needs to enable some Optional
parameters and an OptionsPattern
. The issue I am facing is that the options are being matched to the optional parameters when the optional parameters are excluded.
How do I specify that the optional parameters should use their default when not provided without making multiple function definitions.
With
ClearAll[f]
f[ts_, maxError_, fitAlgorithm_: LinearModelFit, algorithmParams_: {\[FormalX], \[FormalX]},
opts : OptionsPattern[]] :=
<|"fitAlgorithm" -> fitAlgorithm, "algorithmParams" -> algorithmParams, "opts" -> {opts}|>
Then all optional defaults and no options works.
f[1, 2]
<|"fitAlgorithm" -> LinearModelFit, "algorithmParams" -> {\[FormalX], \[FormalX]}, "opts" -> {}|>
However, any additional parameters are misinterpreted
f[1, 2, StepMonitor :> (a = # &)]
<|"fitAlgorithm" -> StepMonitor :> (a = #1 &), "algorithmParams" -> {\[FormalX], \[FormalX]}, "opts" -> {}|>
The StepMonitor
option should be the first item in opts
. Instead it is taken to be the fitAlgorithm
parameter.
I know multiple function defintions will work. For example:
ClearAll[f]
f[ts_, maxError_, fitAlgorithm_, algorithmParams_,
opts : OptionsPattern[]] :=
<|"fitAlgorithm" -> fitAlgorithm, "algorithmParams" -> algorithmParams, "opts" -> {opts}|>
f[ts_, maxError_, opts : OptionsPattern[]] :=
f[ts, maxError, LinearModelFit, {\[FormalX], \[FormalX]}, opts]
f[ts_, maxError_, fitAlgorithm_, opts : OptionsPattern[]] :=
f[ts, maxError, fitAlgorithm, {\[FormalX], \[FormalX]}, opts]
But this is not actually creating optional parameters with default values.
Except + OptionQ
, but it should not work that way :) $\endgroup$ – Kuba♦ Dec 8 '17 at 21:25