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 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.

share|improve this question
    
For this example, Variables works i.e. Variables@expr –  user11946 Mar 4 at 21:48

1 Answer 1

up vote 7 down vote accepted

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}).

share|improve this answer
2  
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!) –  Pinguin Dirk Mar 4 at 11:12
1  
@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,...) –  Pinguin Dirk Mar 4 at 16:50
1  
@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 –  PlaysDice Mar 4 at 18:18
1  
@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? –  Pinguin Dirk Mar 5 at 8:26
1  
@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. –  Pinguin Dirk Mar 5 at 12:41

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.