Reputation: 279
Just curious how Mathematica users debug their code when encounter run-time errors. I feel Mathematica is so powerful that most programming tasks can be replaced with it but when it has bugs the inconvenience of debugging offsets its advantages.
I know Workbench but it's cumbersome to launch and its Java based IDE is kinda slow to compile.
Upvotes: 0
Views: 509
Reputation: 41
The echo function is now built in and is immensely helpful in tracking where errors occur.
"Echo[x_]:=Module[{},Print[x];x]"
For illustration: Finding the number of elements in a list equal to y, after taking modulo 4
input = Range@20;
target = 3;
foobar[list_, y_] := Length@Select[list, y == Mod[4, #] &]
foobar[input, target]
Returns 0 despite there being multiple numbers in the range that work. Modifying foobar for debugging using echo:
foobar[list_, y_] := Length@Select[list, y == Echo[Mod[4, #]] &]
Will quickly reveal that the arguments of Mod are backwards from the desired effect.
Upvotes: 3
Reputation: 1
Trace with a specific argument (what did this function get passed etc) is one useful tool. The most general method, though, is just immediate evaluation of pieces of the code in a working notebook, to locate the first place something happens that you hadn't expected or wasn't in the shape the wrapping code needs etc. It also helps if you write modular code from the start.
Upvotes: 0
Reputation: 4141
Trace and TracePrint can both be handy. I also like to define "any argument" definitions to warn me about undefined calls, such as
f[0] := 1
f[1] := 1
f[n_Integer?Positive] := (f[n]=f[n-1]+f[n-2])
f[wrong___] := ( Print["f had wrong arguments: ",{wrong}]; $Failed)
When in Workbench, those error definitions are great places for breakpoints.
Upvotes: 1