MathGroup Archive 2008

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Thinking Mathematica: Any suggestions?


as you have seen from other posts, an appropriate coding style is a
matter of taste, especially in Mathematica, which lets you use different
approaches. There is absolutley nothing wrong with using procedural
programming style, especially if you do FE or FD like stuff, where most
of what you implement might exist as (pseudo)code in a procedural style,
and having code that reflects the origin is a value in itself. If
efficiency matters (which I think it often does for these kind of
problems), you could also look into Compile, which in my experience
often even works better with a "loop-oriented" coding style, but of
course you'll never get the speed of a well written C or FORTRAN code.
In practice I find every reasonably complex and well written code uses a
decent mixture of loops, functional programming, rule based programming
and what else.

Others have given basically the same advice, but I think one point is
often not made clear (and obviously also a subject of arguments):
Efficiency is not the only, or probably not the best reason to get used
to a more "functional" ore "rule based" programming style within
Mathematica. Used with care, contrary to other statements, I find it
often leads to code that is shorter, less error prone (mainly just
because it avoids indices) and easier to understand.

Example: I think it's easy to guess what the purpose of this one-liner
is, even if the notation of a pure or anonymous function might not be

p2 = Select[numbers, # > 0 &];

while I have to look at this for some seconds longer:

p1 = {};
  If[numbers[[i]] > 0, AppendTo[p1, numbers[[i]]]],
  {i, 1, Length[numbers]}

My advice would be to gradually adopt things like Table, Map, Function,
Select and do this not with only efficiency in mind, but to save you
from typing, debugging and reinventing the wheel...

> I constantly
> find myself looking at the For and Do constructs when attempting to
> implement my algorithms. Obviously, I would like to start thinking in
> "Mathematica" so as to take advantage of what the team at Wolfram has
> done so I don't have to.

Try to think about what you want to achieve, not how you would implement
it, then search the documentation for appropriate terms.
E.g.: I need to _count_ the positive entries within a list -> search for
count, find Count, read the docs, use it.



  • Prev by Date: Re: Thinking Mathematica: Any suggestions?
  • Next by Date: Re: How can I do a "grep -v" equivalent in Import[]?
  • Previous by thread: Re: Thinking Mathematica: Any suggestions?
  • Next by thread: Re: Thinking Mathematica: Any suggestions?