Is it safe to turn off Pattern::patv?

后端 未结 2 1229
北荒
北荒 2021-01-04 23:10

By default Mathematica throws a warning message if I use the same name for both Blank and BlankSequence patterns:

f[{x_, _         


        
2条回答
  •  無奈伤痛
    2021-01-04 23:25

    When you switch the message off and afterwards on again, you write 3 lines to use your pattern. If you want to express that f should take the first element if it's given one list and take all elements if it's given more than one parameter, what's wrong with

    f[{x_, ___}] := g[x];
    f[x__] := g[x];
    

    which is still one line less to write?


    But to give an opinion about your pattern: The problem I see here is

    f[{x_, __} | x__] := {x};
    g[x__ | {x_, __}] := {x};
    f[{1, 2, 3}]
    g[{1, 2, 3}]
    
    Out[6]= {1}
    
    Out[7]= {{1, 2, 3}}
    

    This would be kind of unexpected and maybe hard to debug. Using two definitions with different patterns does the job right:

    f[{x_, __}] := {x};
    f[x__] := {x};
    g[x__] := {x};
    g[{x_, __}] := {x}
    f[{1, 2, 3}]
    g[{1, 2, 3}]
    
    Out[7]= {1}
    
    Out[8]= {1}
    

提交回复
热议问题