Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I have some code that looks like

Table[
    a = 1;
    b = {2, 3}
    c = i;,
    {i, 2}
]

which gives an error:

Set::write: Tag Times in c {2,3} is Protected. >>

In this case, it is quite clear that there is a semicolon missing after b = {2, 3}, which is causing this error. However, sometimes I encounter this in large code blocks spanning several lines, which is very difficult to debug.

How can I automate this semicolon hunting to make debugging easier?

share|improve this question

1 Answer 1

up vote 13 down vote accepted

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

Code for the function:

SetAttributes[findBadSets, HoldFirst]

findBadSets[expr_] :=
  Cases[
    Unevaluated @ expr,
    (Set | SetDelayed)[bad : head_Symbol[___], _]
      /; MemberQ[Attributes@head, Protected] :>
        HoldForm[Row[{head, bad}, Spacer[50]]],
   -1] // Column
share|improve this answer
    
WoW, so useful! –  matheorem Nov 15 '13 at 1:32
    
@matheorem My pleasure. :-) –  Mr.Wizard Nov 15 '13 at 19:03

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.