Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I'm confused as to why Total complains about a nonatomic expression here:

Total[myList] /. {myList -> {1,2}}
Total::normal: Nonatomic expression expected at position 1 in Total[myList]. >>
3

Total[{1,2}]
3

If it's important, here's the context in which I'm using it:

obj = someClass[myList -> {}, anotherList -> {1,2}];
calculateStuff[someClass[props___]] := (1 + Total[myList] * Mean[anotherList]) /. {props};
calculateStuff[obj]
Total::normal: Nonatomic expression expected at position 1 in Total[myList]. >>
0

I can't find any discussion about using a rule to transform a symbol into a list like this. One of the examples in the ReplaceAll documentation makes it seem like this is okay. What am I missing here?

share|improve this question
3  
Well, myList is an undefined symbol (which is atomic), you then apply Total on it. The latter expects a list and it complains about it and returns unevaluated. Only then is the replacement used, which results in Total[{1,2}] and the final result of three. You should have used Total[myList /. {myList -> {1,2}}] instead. This replaces myList before Total is executed. –  Sjoerd C. de Vries Apr 9 at 16:53
    
@SjoerdC.deVries That's what I would use if I were only doing a single Total, my actual function is more complicated so I updated my example to be a little more precise. It would be convenient to only have to do the replacement once, is there no way around it? –  patronics Apr 9 at 17:36

1 Answer 1

up vote 4 down vote accepted

You have to forbid the evaluation of Total[myList] and Mean[anotherList] until you have actually replaced the arguments with the specific lists:

obj = someClass[myList -> {}, anotherList -> {1, 2}];
calculateStuff[someClass[props___]] := 
  Unevaluated[1 + Total[myList]*Mean[anotherList]] /. {props};

calculateStuff[obj]
(* 1 *)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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