# Tag Info

## Hot answers tagged coding-style

52

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

40

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

33

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

33

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

30

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

28

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

28

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

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

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

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

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

14

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

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

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

14

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

14

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

13

It seems to me that this is the correct way to extract values from a nested list of rules: Data ad = {"accept_rate" -> 75, "account_id" -> 395497, "age" -> 41, "badge_counts" -> {"bronze" -> 35, "gold" -> 0, "silver" -> 11}, "creation_date" -> 1326833982, "display_name" -> "Verbeia", "is_employee" -> False, ...

13

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

13

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

13

You can use String "keys" for indexed variables, as I did for A combination of Set::setraw and Set::shape errors. The strings can have spaces or any other characters you want to use: var["Degree of the First Polynomial"] = (* stuff *); You also have a wide range of characters, many of which can be used in Symbol names. Go to menu Palettes > Special ...

12

To my mind, the differences are significant if obscure. The very big difference in evaluation was described already by @Sal. Here are several more subtle ones, which may however bite you. So, functions go first. Functions Can be in two forms, Function[x,x^2] or Function[#^2] (the last is equivalent to #^2&), which are not always equivalent. ...

12

This is not a question of functional style per se. Functional style is, AFAICT, largely about avoiding mutable state (where possible), using functions as fundamental building blocks, using certain abstractions such as higher-order functions, closures, function composition, etc., and avoiding mixing state and behavior. I think that the value of pre ...

10

As Daniel points out, you will always get a good speed-up by compiling. I want to take a different approach and consider how you can get a faster execution by writing your code in a more "functional" style. My machine is slower than yours and ran your code in 17.2 seconds, according to AbsoluteTiming. The first thing I noticed is that you are creating and ...

10

This will give a modest improvement. I'm probably missing a few more though. One other remark: this way of choosing a "random" direction is far from uniform. numparticles = 10^4; numsteps = 10^3; radius = 1.; particles = ConstantArray[{1.001, 0., 0.}, numparticles]; rnew = Map[#.# &, particles]; numcrossings = ConstantArray[0., numparticles]; ...

10

If you're willing to use a slightly different syntax to invoke SystemUtilitiesHashTableAdd, you can create your own wrapper around SystemUtilitiesHashTable that does most of what you want without modifying any built-in functions. The loss of the convenient hashTable.key = value syntax is unfortunately necessary because you can't use TagSet to set a tag ...

10

Two more ways: parti1[a_, p_] := SortBy[a, {Sign[# - p] &, # == # &}] or parti2[a_, p_] := Join[Select[a, # < p &], {p}, Select[a, # >= p &]] With a = {3, 5, 6, 7, 2, 1, 2}; (* and *) p =3 both give {2, 1, 2, 3, 5, 6, 7} Update: While the two methods above and Heike's two methods give exactly the same results, ...

10

There is too much that can be said here so this answer is going to be incomplete but let me give it a shot. First off, With, Block and Module are not interchangeable, in general. To understand when one is preferred you first have to understand how they are different. Performance is not the primary issue here. With[{x=1}, ...] is appropriate when x is ...

10

My general preference is to put the condition as close as possible to the quantity to which it applies: ... to a single argument: f[x_ /; x > 2, y_] := x + y {f[1, 2], f[3, 2]} {f[1, 2], 5} ... to a relationship between arguments: g[x_, y_] /; x > y := x + y {g[1, 2], g[3, 2]} {g[1, 2], 5} ... to a value calculated during the ...

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