Skip to main content
5 of 6
added 12 characters in body
Picaud Vincent
  • 2.5k
  • 15
  • 23

Mimicking named arguments, a good idea? (programming style)

With respect to code readability I really like the possibility, some languages offer, to use keyword (named) arguments.

I would like to have this under Mathematica, but AFAIK there is no native support for that.

By example, to define an inverse gamma distribution, I come with this approach:

createInverseGamma[Mean->m_,Variance->v_]:= With[{a=(m^2+2v)/v,b=m (m^2+v)/v},InverseGammaDistribution[a,b]]; createInverseGamma[Mean->m_,StandardDeviation->std_]:= createInverseGamma[Mean->m,Variance->std^2]; dist=createInverseGamma[Mean->1,StandardDeviation->2] Mean[dist] (* 1 *) Variance[dist] (* 4 *) 

My question: do you see some drawbacks to this approach or do you have a better solution?

nb:

  • clearly some symbols have to be reserved and protected (here I use Mean, Variance etc... that are already defined).
  • this approach can interfere with Option, maybe it would be better to define something like foo[Mean=5] with "=" instead of ->

update:

here is an example with "=" instead of ->

SetAttributes[createInverseGamma,HoldAll]; createInverseGamma[Mean=m_,Variance=v_]:= With[{a=(m^2+2v)/v,b=m (m^2+v)/v},InverseGammaDistribution[a,b]]; createInverseGamma[Mean=m_,StandardDeviation=std_]:= createInverseGamma[Mean=m,Variance=std^2]; dist=createInverseGamma[Mean=1,StandardDeviation=2] Mean[dist] (* 1 *) Variance[dist] (* 4 *) 

However I am even less sure that it has no deleterious side effect...?

Picaud Vincent
  • 2.5k
  • 15
  • 23