The question on making a record like in Mathematica has been discussed in few places, such as Struct data type in Mathematica?.
The problem with all these methods, is that one loses the ability, it seems, to do the
specific extra check on each argument, as in when one does x_?NumericQ
.
My question is: Is there a way in Mathematica to make a record or a struct, and yet be able to use the checking as above on the individual elements?
I am trying to settle down on one method to use as I am tired of having functions called with 10 parameters on them (sometimes one can't avoid this), even when I try to make each function very specific, to minimze the number of parameters, some functions just need many parameters to do the specific job.
First I show the three methods I know about.
Method 1
foo[p_]:=Module[{},
Plot[Sin[x],{x,from/.p,to/.p}]
]
p={from->-Pi,to->Pi};
foo[p]
Advantage: safe, as if I change the symbol 'from' to something else, it will still work. As the following example.
foo[p_]:=Module[{},
Plot[Sin[x],{x,from/.p,to/.p}]
]
p={from->-Pi,to->Pi};
from=-1; (* By accident the symbol from was set somewhere. It will work*)
foo[p]
Method 2
Clear[p,foo];
foo[p_]:=Module[{},
Print[p];
Plot[Sin[x],{x,p["from"],p["to"]}]
]
p["from"] = -Pi;
p["to"] = Pi;
foo[p]
Advantage: also safe, strings are immutable. Do not have to worry about the "from" value changing. But having strings everywhere is not too readable?
Method 3
Clear[p,to,from];
foo[p_]:=Module[{},
Plot[Sin[x],{x,p[from],p[to]}]
]
p[from] = -Pi;
p[to] = Pi;
foo[p]
Disadvantage: if any of the symbols 'from' or 'to' get overwritten somewhere, will cause problem, as in
from=-4; (*accidentally the symbol from is assigned a value*)
foo[p]
So. I think method (1) is the most safe. But now I lose the ability to do this:
foo[from_?NumericQ, to_?NumericQ] := Module[{},
Plot[Sin[x], {x, from, to}]
]
from = -Pi; to = Pi;
foo[from, to]
So, I am hoping to get an idea to be able to combine making a 'record' like, but at the same time, still be able to use the parameter checking on individual elements in the record? Or is this question is not not well posed for Mathematica functional/rule based programming style?
That is one thing I wish Mathematica had, which is a real record to help manage and organize all the variables used in the program.