Hot answers tagged

92

Let's improve the specific cases given. Case #1 Explicit loops are often counterproductive in Mathematica, not only taking more keystrokes, but also more execution time. They are also, in my opinion, more prone to mistakes. Better ways are to use Do, Scan, or Map. Do and Scan are (typically) appropriate for operations that do not accumulate a list of ...


75

Leaving the general discussion on design patterns for some later time, I will try to collect a comprehensive information on some specific design patterns / idioms, one pattern per post. This time it will be memoization Basic memoization What is memoization Memoization is a technique which enables a program to reuse parts of computations it has done ...


63

Update: Mathematica 10 has introduced Association, which can be used as a close equivalent of structs. params = <| "par1" -> 1, "par2" -> 2 |> params["par1"] (* ==> 1 *) In version 10 pure functions can have named arguments, and can be effectively used as expression templates where the slots can be populated from an association. This is ...


62

In this response, I will focus upon the programming paradigm change when moving from Java to Mathematica. I will emphasize two differences between the languages. The first concerns the "feel" of writing Mathematica code. The second is about how iteration is expressed. The "Feel" of Mathematica Java is a reasonably conventional programming language, ...


50

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) ...


46

There are many alternative ways to approach various programming problems that do not use loops and are more efficient (and concise) in Mathematica. Most of them execute faster, but even where they do not, they are faster to type: development time matters, too! Here are some rules of thumb for easier programming and iterating on lists. 1. Most arithmetic ...


40

I prefer the Condition to appear on the left-hand-side and outside the square brackets for several reasons. Type signature I often think of the condition as (part of) the analog of the signature in a typed language, so it should go on the left hand side. Order of operations I like that the elements of the function definition appear in the order in which ...


40

Safety Module is safer than Block because: It is a lexical scoping construct, which means that variable bindings are only tied to a specific piece of code. Variables outside that piece of code are never affected by these bindings. In contrast, Block basically binds a variable to a piece of execution stack, not a piece of code. Such bindings are much ...


37

Linked lists: general discussion I would like to describe here a pattern which is IMO quite important yet seems to be generally under-appreciated and under-used in our community (and probably in Mathematica programming in general) - namely, linked lists. Linked lists are important for several reasons. Here is a (partial) list of benefits they can bring to ...


33

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 Object-oriented-...


31

Using symbols to store data and object-like functions Here are interesting functions to use symbols like objects. (I originally posted these thoughts in What is in your Mathematica tool bag?). The post has grown quite big over time as I used it to record ideas. It's divided into three parts, one describing the function Keys, another one where properties ...


26

StringReplace method After reading other answers I was inspired to write a new method. I place it first because it is almost as concise as the method below yet it is more robust (and safe) because it preserves strings as strings. str = "[can {and it(it (mix) up)} look silly]"; StringReplace[str, {"["|"{"|"(" -> -1, "]"|"}"|")" -> 1, " " -> 0}] //...


23

"Design patterns" are a standard approach to a class of problems. They may become idioms if the community adopts them. They may be simple, but non-trivial to figure out and identify (for oneself) as a pattern worthy of re-use. Here's one particular pattern I personally like to use: Example: the "TransformBy" approach There are functions which transform ...


22

This is a nicely formulated and stimulating question. The answer of course is "Mu". The comment of István Zachar is among those lines... (Here is the official "Mu" link.) Usually when we cannot answer a question in the terms it is asked we extend the paradigm. (E.g. coming up with complex numbers. Or getting enlightened. Or bringing straw men.) So, what ...


22

My path to prefer granularity This is probably more an extended comment and a complementary answer to an excellent one by Anton. What I want to say is that for a long time, I had been thinking exactly along Mr.Wizard's lines. Mathematica makes it so easy to glue transformations together (and keep them readable and understandable!), that there is a great ...


20

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 ...


20

I may be missing the point of this question, but I think it is important to note that ; is the short form of CompoundExpression, and it is not primarily for suppressing output. You can see how ; is interpreted using one of the methods I described here: HoldForm @ FullForm[a; b; c] HoldForm @ FullForm[a; b;] CompoundExpression[a, b, c] CompoundExpression[...


20

str = "[can {and it(it (mix) up)} look silly]"; i = 10; StringJoin @@ Last[Replace[Characters@str, {"[" | "(" | "{" :> Sow[" ", --i], "]" | ")" | "}" :> Sow["", ++i], c_ :> Sow[c, i]} , 1] ~Reap~ Range@10] (* " mix it up and it can look silly" *) This just scans through the characters one at a time and Sows them with an integer tag. ...


19

rcollyer has answered the question you actually asked, but I wondered if there wasn't an easier way to code this. If I understand your original code correctly, you want to save the final state of the pond after ten fishing decisions, as well as the total number of fish caught in that sequence of fishing decisions, and the list of fishing decisions. You can ...


19

This is just a beginning of some notions of what the patterns of Mathematica programming might be. Others should feel free to add or correct anything here. It might well be that I've simply misunderstood what patterns in software development really are. Pattern-based overloading to create polymorphous functions It's pretty common to use Mathematica's ...


19

I know that you are thinking ahead and considering how to make the work flow easiest for yourself. Nevertheless, in reading over your question I suspect you are pointed in the wrong direction and will only make things more difficult and burdensome for yourself. What you are talking about is writing Mathematica Applications. (I would start with a single ...


18

You cannot make assignments to First, Last, Rest, or Most the way you can with Part. Therefore, there is greater consistency in using Part for all operations. See this answer for an example of and argument for this consistency. Also, you must change functions if you need to update your code to index a different element or change an element to a Span. By ...


18

Update: Athanassios correctly pointed out that my attempt to set defaults doesn't work. The problem appears to be that the absence of the element from the first list (ad) causes the defaults list to never be checked. A condensed exhibit: ad = {"accept_rate" -> 80, "badge_counts" -> {"bronze" -> 39, "silver" -> 9}}; defaults = {"age" -> ...


18

Description In software engineering, it is a good practice to comment your code. I would advise you to utilise comments to partition your code in a following way. Additionally, if you have ever worked with any other programming languages, you could employ indentation. Alternatively, you could modularize your application as to develop it in smaller, more ...


17

I appear to be in the minority but I never write big blocks of Mathematica code, it's just too difficult to read. The way I look at it you have to consider how a reader will understand your app. So I make the main block very small, like this: Manipulate[ Row[{ vectorPlotAndTrajectory[y0, b], Show[fy, position[y0, b]] }] , {b, -7.99, 8} , {{y0, 2}...


16

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 ...


16

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 ...


16

As no one gave a FixedPoint answer, here is one: preparedStr = StringReplace[ "((your[drink {remember to}]) ovaltine)", { RegularExpression["[{[(]"] -> "{", RegularExpression["[)\]}]"] -> "}" }] "{{your{drink {remember to}}} ovaltine}" lst = {}; ...


15

Reasons why adding rules to Set is a really bad idea First, let me list the reasons why I think that adding rules to Set globally is a very bad practice: This is a hugely non-local system modification. We have no idea which parts of the system will be affected, but we can be sure that there will be many. Set is a very frequently used command (see first ...


15

How about operations like arithmetic on lists, matrixes, & tensors or Dot and DotProduct? list1 = {a, b, c}; list2 = {d, e, f}; matrix1 = {{a, b, c}, {d, e, f}}; matrix2 = {{a, b, c}, {d, e, f}, {g, h, i}}; tensor1 = {{{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}}, {{{a, b, c}, {d, ...



Only top voted, non community-wiki answers of a minimum length are eligible