I have a function func[x], which is rather slow to evaluate. It gets called (multiple times) inside other expressions; I'd like to know how many times it gets called (without actually evaluating the expression). (This is so I can estimate how long it will take.) For example, I'd like to make a function that would take 3x*Hold[func[4]]+Hold[func[5]]*Hold[func[6]] and return 3, because func would get called three times if I ran the code (with ReleaseHold).

I was thinking that string matching would be the way to go, namely come up with a list of symbols in 3x*Hold[func[4]]+Hold[func[5]]*Hold[func[6]], convert that into a list of strings, and then count the number of times func appears, but I haven't figured out a way to do the first two steps.

To be clear, I know that I'm always calling my function in expressions like the above, in which it's going to be evaluated once, so I only need to count the number of times "func" appears.

Help/ideas would be appreciated.


Have you looked at Count?

expr = HoldForm[3 x*func[4] + func[5]*func[6]]
Count[expr, func, ∞, Heads -> True]


  • $\begingroup$ Thanks! Yes, I had tried count, but I was missing the "Heads->True", which makes it work. Could you explain what that does? $\endgroup$ – Lauren Pearce Oct 17 '16 at 1:11
  • $\begingroup$ @LaurenPearce. Rather than me write an explanation that would just quote the docs, I suggest you look at this documentation article on the Heads option. Bear in mind that you are using func as a head in your expression. $\endgroup$ – m_goldberg Oct 18 '16 at 13:34

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.