1
$\begingroup$

Suppose c[i,t] is an array such as c[1,2]={1,2,3}

I want to define a function TOT[c[i,t]] which, for instance, computes Total[Array]. This does not work:

TOT[c[i_,t_]]:=Total[c[i,t]]

Any help?

$\endgroup$
  • $\begingroup$ I don't understand the question. Is c[i_, t_] a function that returns a one-dimensional list? If so, then c[1, 2] // Total should give you what you want. $\endgroup$ – Shredderroy Jul 25 '19 at 21:48
  • 3
    $\begingroup$ Writing the definition as TOT[c[i_, t_]] := Total[c[i, t]] is problematic because your expression likely does not retain the Head c when passed to TOT. Try something like TOT = c /* Total. Then TOT[1, 2] = Total[c[1, 2]], which seems to be what you want. $\endgroup$ – Shredderroy Jul 25 '19 at 21:52
3
$\begingroup$

You can use the HoldFirst attribute on your TOT function:

c[1, 2] = {1, 2, 3};

SetAttributes[TOT, HoldFirst];
TOT[c[i_, t_]] := Total[c[i, t]]

TOT[c[1, 2]]
(*    6    *)
$\endgroup$
  • $\begingroup$ This is is exactly what I wanted. Thank you so much. $\endgroup$ – Farhad Jul 26 '19 at 7:12
  • $\begingroup$ It is generally a good practice to set Attributes before any definitions because attributes also affect how patterns on the lhs are treated. $\endgroup$ – Anton.Sakovich Jul 26 '19 at 12:45
  • $\begingroup$ Thanks @Anton.Sakovich for the hint, I've updated the submission. $\endgroup$ – Roman Jul 26 '19 at 13:06
2
$\begingroup$

Why not simply:

c[1, 2] = {1, 2, 3};

TOT[lst_] := Total[lst]

TOT[c[1, 2]]
(* 6 *)
```
$\endgroup$
  • $\begingroup$ or even TOT=Total $\endgroup$ – evanb Jul 26 '19 at 6:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.