Hot answers tagged design-patterns
38
It is a simple way to implement Memoization. The trick is that if you define a function as
f[x_]:=f[x]=ExpensiveFunctionOf[x]
then when you for the first time call e.g. f[3], it will evaluate as
f[3]=ExpensiveFunctionOf[3]
which will evalulate the expensive function, and assign the result to f[3] (in addition to giving it back, of course). So if e.g. ...
35
This answer may be unacceptable right from the outset because it uses undocumented functions. However, it has advantages over some of the approaches suggested so far which might be redeeming enough in certain scenarios to recommend it in practice. In particular, it provides totally encapsulated state (unlike, e.g., DownValues or Temporary symbols) and O(1) ...
31
Memoization is perhaps the most common application, but it is not the meaning of that construct.
More generally it is a construct for a function that redefines itself. This has many uses beyond memoization. Consider this function:
f[y_] := (f[y] = Sequence[]; y)
This function is used to remove duplicates in a list. It works because after the first ...
26
There were several attempts to emulate structs in Mathematica. Emphasis on emulate, since AFAIK there is no built - in support for it yet. One reason for that may be that structs are inherently mutable, while idiomatic Mathematica gravitates towards immutability. You may find these discussions interesting:
Struct-data-type-in-mathematica
...
24
Quoting the OP's comment:
Most of the work I do involves constructing mathematical models and
then testing various scenarios against those models. I'd like to be
able to populate a particular scenario and then pass that scenario to
a model. I'd also like to be able to copy that scenario, modify one or
more parameters, and then pass the new ...
24
It's ... oh, why not let the docs speak:
tutorial/FunctionsThatRememberValuesTheyHaveFound
(in Doc center)
Edit
You may also find additional information by searching for "memoization" on this site. This has always been a great trick to avoid having to re-evaluate the result of a computationally intensive function call. In the above link, it is also used ...
21
This is my first reply in this group. So please bear with me if I make any mistake, it would not be intentional, just lack of familiarity with the rules.
Although the replies above mention important aspects, I generally like to view things from alternative perspectives. I'd like to offer a few of those on this question. Understanding is enhanced by viewing ...
17
Format is what you are looking for: Create a data structure, something like this:
mkMyData[d1_, d2_] := MyData[d1, d2]
GetD1[a_MyData] := a[[1]]
GetD2[a_MyData] := a[[2]]
Format[MyData[d1_, d2_]] := "MyData[<" <> ToString[Length[d1] + Length[d2]] <> ">]"
Call the constructor:
data = mkMyData[Range[5], q]
(*
"MyData[<5>]"
*)
...
17
It is probably debatable to what extent it has built-in object oriented features.
In any case, this answer is not intended to lead you to try to emulate object oriented programming, which is in general a bad idea. (see @Leonid 's answer)
However, it is not debatable that Mathematica is tremendously flexible (as to style and notation at least, the evaluation ...
15
At the risk of repeating myself, I would like to stress that one has to be critical towards the superficial flexibility offered by Mathematica, when (particularly mutable) data structures are concerned. Using mutable data structures assumes a programming style for which Mathematica is not optimized. It can emulate it, yes, and we have seen a number of such ...
15
The answers already posted show that built-in Mathematica functionality can be used to get the meaningful functionality provided by a C struct. If you want your code to be readable by other Mathematica users, I suggest using a list of rules as already advised above.
However, if you really want struct-style syntax I'll offer an implementation that I've ...
13
So the naive way to set up a data structure like struct is, as the OP suggested, to simply used DownValues and/or SubValues. In the below, I use SubValues.
Copying the Wikipedia C language struct example
struct account {
int account_number;
char *first_name;
char *last_name;
float balance;
};
struct account s; // Create new account labelled s
...
13
I think the simple answer is, there isn't one, but you could always just use UML itself, particularly for behavioral diagrams, even if the code isn't object oriented. You wouldn't use class or object diagrams, but there is nothing to stop you from using, say, a component diagram.
You may find the tutorial and white paper on building large software systems ...
12
It also has another practical side. If you have a random function, which
you only want to evaluate once, but
you don't know where exactly it will be evaluated or
you want to declare it before the parameters it depends on are defined, and
you want it to be the same after the first evaluation, for any subsequent call,
you can use the memoization trick:
...
10
I arrived very late to this party and I'm very much afraid that nobody comes here anymore. Still I'm posting this in hope that an occasional visitor may find it a practical approach to implementing data structures with named fields within Mathematica.
The concept
The idea is to use protected symbols to name a structure and its fields. The symbol that names ...
9
As Michael Pilat explained here it is more robust to use MakeBoxes, rather than Format.
Using MakeBoxes:
MakeBoxes[diag[m_?MatrixQ], _] ^:=
InterpretationBox[RowBox[{"diag", "[", #, ",", #2, "]"}], diag[m]] & @@
ToBoxes /@ {Dimensions[m], Diagonal[m]}
Here is a definition for handling Part extraction:
diag[m_?MatrixQ][[part___]] ^:= m[[part]]
...
7
The answer to the more general question of how necessary "software architecturizationing" is in Mathematica is, in short: Not that necessary.
The reason is basically 1) lists 2) dynamic typing and 3) lists + dynamic typing. For example, Mathematica doesn't need classes/OO because lists allow you to represent a huge swath of data structures. You would gain ...
4
I don't know a way with subvalues, but you can use Module to create objects without explicit identifier in makeObj:
makeObj[] := Module[{field = 0},
Switch[#,
"increase", field++; #0,
"field", field]&]
(Note that I slightly changed your "increase" function to return #0, that is, "self", so I can chain ...
3
Well, one obvious idea would be to build on the struct implementation by Bob Beretta. You would have to add information about methods and modify the implementation of --> to consider those as well, and for polymorphism, you'd also have to store the base class (or base classes, if multiple inheritance should be supported), and have --> look there if the ...
Only top voted, non community-wiki answers of a minimum length are eligible

