I have an expression like this:

expr = F[0, 1] + 2 F[0, 0] - 17*F[2, 0]

and I want to transform it to a list consisting of all function calls with its arguments:

MyList = {F[0, 1], F[0, 0], F[2, 0]}

Does anyone know a clever way to do this in Mathematica?

My currently best solution is using ToString and do string-manipulations, but it is defintivly very slow and ugly.

  • $\begingroup$ For this example, Variables works i.e. Variables@expr $\endgroup$ – user11946 Mar 4 '14 at 21:48

E.g. using Cases:

Cases[expr, _F, Infinity]

{F[0, 0], F[0, 1], F[2, 0]}

Note that the 3rd argument is the levelspec. See e.g. expr//FullForm why it's needed

EDIT (I wasn't careful!)

Note that this does not work for

expr = F[0,0]

as by default, Cases does not match the whole expression (it starts at level 1).

If that could be the case, you can use:

Cases[expr, _F, {0,Infinity}]

Also, see @YvesKlett's comment for levelspec -1 (or {0,-1}).

  • 2
    $\begingroup$ I am glad you like it & I am kinda proud you take that as a start learning more about MMA (or whatever that language is called these days)! Don't accept to hastily, there might be other (maybe even nicer ways) to get what you like, you don't want to scare them away, do you? :) (and try to be active in here, that's how I learnt a lot!) $\endgroup$ – Pinguin Dirk Mar 4 '14 at 11:12
  • 1
    $\begingroup$ @PlaysDice: well, as long as you can make a pattern, it should work. Is there a concrete example you have in mind? (I would suggest not using capitals for that, as many of them are reserved (such as E, C, D,...) $\endgroup$ – Pinguin Dirk Mar 4 '14 at 16:50
  • 1
    $\begingroup$ @PinguinDirk using OP as a template, expr=func1[0,1]+ 2 elephant[2,3] - 17*unicorns[5,6] but without using func1|elephant|unicorns in Cases $\endgroup$ – PlaysDice Mar 4 '14 at 18:18
  • 1
    $\begingroup$ @PlaysDice: well, assuming you want to retrieve the functions on the second but last level (and thus: not nested like func1[0,func2[1]]), you could e.g. use Cases[expr, _, {-2}]. Is that what you are looking for? $\endgroup$ – Pinguin Dirk Mar 5 '14 at 8:26
  • 1
    $\begingroup$ @PlaysDice: based on the example he gave I figured that the identifying pattern of the items to select is the head F. Thus my solution. But you are right, assuming he doesn't nest, it will work just as well. $\endgroup$ – Pinguin Dirk Mar 5 '14 at 12:41

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.