Re: Overloading mathematica built in functions

*To*: mathgroup at smc.vnet.net*Subject*: [mg5749] Re: [mg5716] Overloading mathematica built in functions*From*: Allan Hayes <hay at haystack.demon.co.uk>*Date*: Tue, 14 Jan 1997 10:42:28 -0500*Sender*: owner-wri-mathgroup at wolfram.com

seanross at worldnet.att.net [mg5716] Overloading mathematica built in functions writes >I want to add a capability to the Sum function. If I give it a >single argument that is a 1-D list, I want it to sum the list. > >Unprotect[Sum]; >Sum[f_List]:=Sum[f[[i]],{i,1,Length[f]}]; >Protect[Sum]; > >does not work. Does anyone know why? I am guessing it has >something to do with the attribute HoldAll on the built-in function >Sum. Sean, Yes, it is because of the HoldAll attribute: if w = {1,2,3}; then in Sum[w], w is not evaluated to a list and the definition is not used. But, with Unprotect[Sum]; Sum[f_/;Head[f]===List]:=Sum[f[[i]],{i,1,Length[f]}]; Protect[Sum]; The test is evaluated (in spite of the HoldAll) and we get Sum[w] 6 However, the following is much more faster Sum[f_/;Head[f]===List]:= Plus@@f; And even here, f is evaluated twice, so the following variant may be better Sum[f_]:= Module[{g},Plus@@g/;Head[g = f]===List]; Allan Hayes, hay at haystack.demon.co.uk http://www.haystack.demon.co.uk