Preventing avalanche of runtime errors in Mathematica

后端 未结 5 1085
悲哀的现实
悲哀的现实 2020-11-27 18:19

A typical situation I run into when notebook grows beyond a couple of functions -- I evaluate an expression, but instead of correct answer I get Beep followed by do

5条回答
  •  青春惊慌失措
    2020-11-27 18:34

    What I'd love to get is a way to define a general procedure to catch error propagation without the need to change radically the way I write functions right now, preferentially without adding substantial typing.

    Here is a try:

    funcDef = t_[args___]  :c-:  a_ :> ReleaseHold[Hold[t[args] := 
                             Check[a, Print@Hold[a]; Abort[]]]];
    Clear@v;
    v[x_, y_] :c-: Sin[x/y] /. funcDef;
    ?v
    v[2, 3]
    v[2, 0] 
    

    The :c-: is of course Esc c- Esc, an unused symbol (\[CircleMinus]), but anyone would do.

    Output:

    Global`v
    v[x_,y_]:=Check[Sin[x/y],Print[Hold[Sin[x/y]]];Abort[]]
    
    Out[683]= Sin[2/3]
    
    During evaluation of In[679]:= Power::infy: Infinite expression 1/0 encountered. >>
    
    During evaluation of In[679]:= Hold[Sin[2/0]]
    
    Out[684]= $Aborted
    

    What we changed is

           v[x_, y_] := Sin[x/y]
    

    by

           v[x_, y_] :c-: Sin[x/y] /. funcDef;  
    

    This almost satisfies my premises.

    Edit

    Perhaps it's also convenient to add a "nude" definition for the function, that does not undergo the error checking. We may change the funcDef rule to:

    funcDef = 
         t_[args___]  \[CircleMinus] a_ :> 
    
                {t["nude", args] := a, 
    
                 ReleaseHold[Hold[t[args] := Check[a, Print@Hold[a]; Abort[]]]]
                };  
    

    to get for

     v[x_, y_] :c-: Sin[x/y] /. funcDef;  
    

    this output

    v[nude,x_,y_]:=Sin[x/y]
    
    v[x_,y_]:=Check[Sin[x/y],Print[Hold[Sin[x/y]]];Abort[]]
    

提交回复
热议问题