Return equality from Mathematica function

后端 未结 4 1214
小蘑菇
小蘑菇 2021-01-23 16:51

I have a function that returns equalities, which I want to print, for example, x==y, or 2x+5==10. These usually have no meaning for mathematica, it cannot simplify it furhter.

4条回答
  •  天命终不由人
    2021-01-23 17:18

    Usually one uses HoldForm for this sort of thing. HoldForm is a head that works like Hold, in that it doesn't evaluate its contents, but it's not displayed when it's printed as output, like so:

    In[1]:= HoldForm[x == 3]
    Out[1]= x == 3
    
    In[2]:= HoldForm[x == x]
    Out[2]= x == x
    

    As with Hold, you can interpolate things into a HoldForm using With or function argument substitution, like so:

    In[3]:= PrintableEqual[x_, y_] := HoldForm[x == y]
    
    In[4]:= PrintableEqual[x, x]
    Out[4]= x == x
    

    However, this will mean that the arguments are evaluated before substitution, like so:

    In[5]:= PrintableEqual[x + x, 2 x]
    Out[5]= 2 x == 2x
    

    If you don't want this to happen, you can use SetAttributes and HoldAll:

    In[6]:= SetAttributes[PrintableEqual, {HoldAll}]
    
    In[7]:= PrintableEqual[x + x, 2 x]
    Out[7]= x + x == 2 x
    

    Note that HoldForm is always there, it's just not displayed in output form:

    In[8]:= PrintableEqual[x, x] // InputForm
    Out[8]= HoldForm[x == x]
    

    If you want to evaluate things, use ReleaseHold:

    In[9]:= ReleaseHold@PrintableEqual[x, x]
    Out[9]= True
    

提交回复
热议问题