Tag Info

Hot answers tagged

79

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


67

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


57

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


55

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


47

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


44

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


37

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


33

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


32

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


32

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


30

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


23

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


21

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


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


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

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


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


17

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


17

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


17

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


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


15

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


15

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


15

This is a straightforward attempt at a recursive descent parser, favoring readability over brevity. First, the tokenizer: tokenize[str_] := DeleteCases[StringCases[str, { "(" -> open[1], "[" -> open[2], "{" -> open[3], ")" -> close[1], "]" -> close[2], "}" -> close[3], x : (Except[Characters["()[]{}"]] ..) ...


15

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 = {}; ...


14

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


14

No, they are not needed. You can specify as many "iterators" (the parameters of the form {x, xmin, xmax} or {x, xmin, xmax, dx}) as you wish. (See the last form list in the documentation.) For example, Table[i j, {i, 3}, {j, 3}] produces {{1, 2, 3}, {2, 4, 6}, {3, 6, 9}} Additionally, any iterator can rely on those that came before it, but not those ...


14

This seems to work: With[{n = Length@f[0]}, Plot[Evaluate[Hold[f[x][[#]]] & /@ Range[n]], {x, 0, 1}]]


14

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


14

As described by Andy Ross in a comment, you can make a definition that preprocesses the argument(s) into a canonical form. Turning his example around simply to illustrate flexibility: f[{args__}] := f[args] f[args__] := Multinomial[args] / Plus[args] f[{12, 7, 3}] == f[12, 7, 3] True This method is useful for more complicated preprocessing, but in ...



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