Conditional statement in function

It seems the equality condition does not work as expected.

deq[m_] := If[m===0,p+1,2 (p+1-m)]
dle1[m_] := Sum[ deq[i],{i,0,m} ]
dle2[m_] := Sum[ deq[i],{i,1,m} ] + (p+1)

Echo[dle1[p]]
Echo[dle2[p]]


Here is the output

In[5]:= >> (1 + p) (2 + p)

Out[5]= (1 + p) (2 + p)

In[6]:=               2
>> 1 + 2 p + p

2
Out[6]= 1 + 2 p + p


It may be because the symbol i is not replace by 0. I tried with == but it doesn't work neither.

• Do you have a numerical value for p? How is Sum supposed to know how many terms to sum over? Also you definitely want m == 0. If I make that change and evaluate dle1[5] I get a totally reasonable result. Commented Mar 21, 2020 at 21:56
• What did you expect actually? You don't need Echo. Commented Mar 21, 2020 at 22:50
• b3m2a1 : it is just linear in m, it should be able to compute the sum with p being not set. I do not want to fix p to a numerical value @Pierre ALBARÈDE, I expect the Out[6]. It seems that for Out[5] he replaces dle1[0] by $2 (p+1)$ instead of $2p$, Commented Mar 21, 2020 at 22:59
• Can you post the respective inputs In[5] In[6]? You can copy cell as Input text and paste here. Like In[73]:= 2 + 3 Out[73]= 5 Commented Mar 21, 2020 at 23:19

As mentioned by b3m2a1 in the comment. Using == instead of === results in the correct result:

deq[m_] := If[m == 0, p + 1, 2 (p + 1 - m)]
dle1[m_] := Sum[deq[i], {i, 0, m}]
dle2[m_] := Sum[deq[i], {i, 1, m}] + (p + 1)

dle1[p]
(* Piecewise[{{1 + p, p <= 0}}, 1 + 2*p + p^2] *)

dle2[p]
(* 1 + p + Piecewise[{{2*p, p == 1}}, p + p^2] *)


The output involves Piecewise, but it's easy to notice the result is correct.

Then why does === cause problem here? We turn to Trace:

deq[m_] := If[m === 0, p + 1, 2 (p + 1 - m)]
dle1[p] // Trace


As we can see, deq[i] is evaluated inside Sum, and i === 0 evaluates to False, so deq[i] becomes 2 (p + 1 - m), which is undesired. That's al——

No, that's not the end.

If you know a little about attribute, you may feel surprising that deq[i] is evaluated inside Sum: Sum owns the attribute HoldAll! This is because a function with attribute HoldAll only holds the argument of function. Once the argument goes into the function, there's no guarantee it'll never be evaluated. A simple example:

ClearAll[f, g]
Attributes[f] = {HoldAll};
Attributes[g] = {HoldAll};
g[a_] := a

f[1 + 1]
(* f[1 + 1] *)
g[1 + 1]
(* 2 *)


The following is another example about functions with HoldAll attribute evaluating their arguments internally:

Inconsistency between Plot and NIntegrate

You get what you expect, if you don't use Setdelayed := for fundtion definitions.

{deq[m_] = If[m == 0, p + 1, 2 (p + 1 - m)],
dle1[m_] = Sum[deq[i], {i, 0, m}],
dle2[m_] = Sum[deq[i], {i, 1, m}] + (p + 1),
dle1[p],
dle2[p]} // Simplify // TableForm


• Actually := isn't related here. It's all because you've used === instead of ==. Commented Apr 21, 2020 at 9:47