Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up a "struct" in Mathematica safely

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.

like image 851
Nasser Avatar asked Sep 09 '11 02:09

Nasser


1 Answers

First, I'd like to mention that all the methods you listed are IMO flawed and dangerous. The main reason why I don't like them is that they introduce implicit dependences on global variables (the reasons why this is bad are discussed e.g. here), and can also mess up with the scoping. Another problem of them is that those approaches look like they won't scale nicely to many instances of your structs existing simultaneously. The second method you listed seems the safest, but it has its problems as well (strings as field names, no way to type-check such a struct, also symbols used there may accidentally have a value).

In my post here I discussed a possible way to build mutable data structures where methods can do extra checks. I will copy the relevant piece here:

Unprotect[pair, setFirst, getFirst, setSecond, getSecond, new, delete];
ClearAll[pair, setFirst, getFirst, setSecond, getSecond, new, delete];
Module[{first, second},
   first[_] := {};
   second[_] := {};
   pair /: new[pair[]] := pair[Unique[]];
   pair /: new[pair[],fst_?NumericQ,sec_?NumericQ]:= 
      With[{p=new[pair[]]}, 
          p.setFirst[fst];
          p.setSecond[sec];
          p];
   pair /: pair[tag_].delete[] := (first[tag] =.; second[tag] =.);
   pair /: pair[tag_].setFirst[value_?NumericQ] := first[tag] = value;
   pair /: pair[tag_].getFirst[] := first[tag];
   pair /: pair[tag_].setSecond[value_?NumericQ] := second[tag] = value;
   pair /: pair[tag_].getSecond[] := second[tag];       
];
Protect[pair, setFirst, getFirst, setSecond, getSecond, new, delete]; 

Note that I added checks in the constructor and in the setters, to illustrate how this can be done. More details on how to use the structs constructed this way you can find in the mentioned post of mine and further links found there.

Your example would now read:

foo[from_?NumericQ, to_?NumericQ] :=
   Module[{}, Plot[Sin[x], {x, from, to}]];
foo[p_pair] := foo[p.getFirst[], p.getSecond[]]
pp = new[pair[], -Pi, Pi];
foo[pp]

Note that the primary advantages of this approach are that state is properly encapsulated, implementation details are hidden, and scoping is not put in danger.

like image 165
Leonid Shifrin Avatar answered Oct 17 '22 03:10

Leonid Shifrin