# Tag Info

## Hot answers tagged debugging

34

While I wait for better answers from some very knowledgeable people in the matter on the site, I'll write what I'm thinking... I think that most of your problems are due to lack of practice with functional thinking rather than lack of debugability itself. I think one that on the contrary, one of the advantages of programming functionally is that the state ...

27

While I agree that the debugging tools could have been better developed by now, let me just throw in a few notes and links. Function chaining (f[g[h[...]]]): I'd argue that this is a good thing. Why: Functions return expressions, which are immutable. You don't introduce as much state (or at all), as in imperative languages. This makes it easier to debug ...

27

Like in other programming languages, such as C or Java, assertions are used to catch errors in the logic of your code. With discipline, you can also use exceptions for a similar purpose (see e.g. this discussion for an example). Using patterns and returning a function unevaluated is useful in different types of situations. The linked above answer also ...

25

Preamble It is hard to say what exactly is causing this without seeing the code, but, assuming that there are no memory leaks in the built-in functions you are using, I am only aware of a very few possible causes for memory leaks in Mathematica. Since almost anything is immutable, the leaks must be associated with some symbols for which definitions are ...

19

I found a curious style of debugging that I call "Epicsauce Debugging Level 2." First you type this: x = 0; While[True, Pause[1]; (*Dynamic[x]*) x++ ]; Then you highlight the Dynamic[x] and press Ctrl+Shift+Enter. Then you execute the cell and BE AMAZED!!! It's quite hilarious, but I wonder how useful it would be for more serious code. I've already ...

17

Let me first answer your second question, since I can only guess about the main question: I also observed that the syntax colouring (version 10, windows 7) suggests that Trace can be used with only two arguments. It's really just the coloring that goes wrong and has nothing to do with functionality. You can see that it is not even related to ...

16

Here is a function findBadSets that will find any explicitly bad Set/SetDelayed attempts in a given expression. Simply wrap it around a syntactically complete block of code, or follow the block with // findBadSets and the errors are printed one per row, protected symbol followed by complete left-hand side for each bad Set: (* your example *) // findBadSets ...

16

(It's interesting I asked a similar question before. As your question is a superset of mine, I would like to post the answer here.) About the first question: How does the debugger know what to highlight? I don't really know the internal mechanism, but I hope this answer can provide some possible tiny clues. About the second question: Can we influence this ...

16

Normally I like to use On and Off for this kind of tracing as it is easy to set up without modifying any symbols. However, it does not immediately work in this case: On[Roots] Solve[x^3 - 2 x + 12 == 0, x]; Off[] This does not produce any trace messages. Something must be using Quiet to suppress them. We can check this hypothesis: On[Quiet] Solve[x^3 ...

15

There's absolutely no need to load a package if all you want to do is simple Gauss-Legendre quadrature: GaussLegendreQuadrature[f_, {x_, a_, b_}, n_Integer: 10, prec_: MachinePrecision] := Module[{nodes, weights}, {nodes, weights} = Most[NIntegrateGaussRuleData[n, prec]]; (b - a) weights.Map[Function[x, f], Rescale[nodes, {0, 1}, {a, ...

15

There are indeed some open source alternatives, as other posters have suggested, but you will miss the unique facilities of WB to develop state of the art documentation. So if you want to develop some serious work in MMA, for yourself or others, you should seriously consider WB. Having said that, I use WB in a (probably) unconventional way. Within WB you can ...

14

There is also a TextMate bundle for Mathematica: https://github.com/dehowell/mathematica-tmbundle TextMate is for Mac only, but this bundle work in other editors like Sublime Text (multi platform) (windows)

14

QuantityForm (and some other formatting functions) issues messages at typesetting instead of evaluation, and Trace is generating output that is in an unevaluated state, which QuantityForm isn't expecting. Here's a couple of similar examples: Trace[Block[{form = "LongForm"}, QuantityForm[Quantity[1, "Meters"], form]]] Trace[Block[{digits = 3}, ...

12

There is a certain impedance mismatch between lines of code and Mathematica expressions, because Mathematica code is written more or less directly in the parse trees, and the syntax (which encourages nested expressions) was not particularly designed to make lines a really good concept here. That said, this would be a problem in any language, to various ...

12

You can enter arbitrary expressions in the Expressions debugging view: The function VariableValue must be used in such expressions in order to access any active variables. If the Expressions view is not visible, you can open it from the Workbench main menu using Window / Show View... / Expressions.

11

My first instinct in such cases is usually to use Trace to figure out which part of the evaluation is behaving differently from what I expect. For the example you already have this point isolated. Then I typically try to dissect it and determine why it misbehaves. An important part of this dissection is using FullForm to remove all the shorthands that are ...

11

This is admittedly messy, but something along these lines might work: insertBelowEvaluationCell[expr_] := (SelectionMove[EvaluationNotebook[], After, EvaluationCell]; NotebookWrite[EvaluationNotebook[], Cell[BoxData@ToBoxes[expr], "Print"]]) This function moves the insertion point just below the evaluation cell before inserting the text or ...

11

In the original article there is a semi-colon after the final Show in tile. Remove that semi-colon and the program should run normally. While you're at it, replace GraphicsArray with GraphicsGrid. You probably also noted that the article uses unusual color names that Mathematica does not recognize. (The package, Graphics Colors is not found.) You will need ...

10

This is a memory leak in HistogramList: You can reclaim the memory by evaluating Remove["**modelData\$*"]

10

This version of ShowIt first shown by Leonid Shifrin is particularly useful, it can be used in conjunction with the function ReapTags defined below also. It now uses the LetL function also from Leonid defined here (in order to avoid a nested With for printedExpr). I've incorporated the answer of Szabolcs to the question Is it possible to Print expressions ...

10

Why complicate it? a[[3 ;; 4, 2 ;; 4]] = b; Here is a general function. It take a main matrix, and a sub matrix. It puts the sub matrix inside the main matrix. All what you have to do is just tell it the starting row number and starting column number for where to insert the sub matrix at. Updated: Added pattern checking on arguments. Added additional ...

10

Well, here is a suggestion: you can overload Needs using Villegas-Gayley trick. To do this safely, here is a generator for local environments, where Needs will be overloaded: createTraceEnvironment[context_String]:= Module[{inNeeds}, Function[ code, Internal`InheritedBlock[ ...

10

Monitor For the trivial example shown in the question, we could use Monitor to watch the global variable sum change in real time: Monitor[aSummer[10], sum] But, in general, we will probably not be so lucky that the variable or expression that we wish to monitor happens to be global -- that's why we were using Trace in the first place. TracePrint ...

9

The debugger in Mathematica is, in fact, a bit hard to use. However, it is functional. To create a breakpoint, one must select the WHOLE command. Just double clicking on the command name will do. Then you press the "Break at Selection" button in the debugger control panel. I still have no clear understanding what is considered a whole command from the ...

9

Implementation Here is a better version of my debug function posted here, which would print the stack on the first message generated, and abort the computation. I have used it extensively with great effect in many cases. This constructs the nested OpenerView from an arbitrary expression: ClearAll[openerDress]; SetAttributes[openerDress, HoldAll]; ...

8

I gave my answer to this question here: http://mathematica.stackexchange.com/a/3146/121 Let me show how those recommendations apply to this specific problem. 1. Expanding the selection with Ctrl+. Using Ctrl+. on a few parts would quickly show something like this: This would alert you that something strange is going on. 2. Displaying the expression ...

8

Assuming your code is not too messy, you may have some luck with the built-in debugger. Go to Evaluation and check on Debugger. It will open a new panel, where you should have "Break at messages" checked. After that, Mathematica will highlight the error for you with a green box:

7

Maybe TracePrint[g[1], TraceOff -> f] ?

7

This is an arguably even messier solution than Szabolcs', and its performance isn't going to win any awards, but it has some (somewhat dubious) advantages: It allows you to choose whatever target you want for the printing, putting things in an arbitrary notebook, and the output will appear at the current selection in that notebook; After that, printing ...

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