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.

This question already has an answer here:

Why does

Flatten[f[g[a, f[b]], f[c, d]]]

result in

f[g[a, f[b]], c, d]

I expected the answer to be

f[g[a, b], c, d]

What is wrong in this code?

share|improve this question

marked as duplicate by Mr.Wizard Jun 27 at 9:32

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

5  
See the third entry under the details for Flatten in the documentation: Since the head is f, only those subexpressions of it that are also f get flattened. –  ciao Jun 16 '14 at 7:13
    
Related question here –  m_goldberg Jun 16 '14 at 7:29
    
Thank you! I think i know what the reason is.the hyperlink let me enlightened. –  user15961 Jun 16 '14 at 7:56

2 Answers 2

up vote 8 down vote accepted

Compare:

Flatten[f[g[a, f[b]], f[c, d]]]

(* f[g[a, f[b]], c, d] *)

Flatten[k[g[a, f[b]], f[c, d]]]

(* k[g[a, f[b]], f[c, d]] *)

Note the second does... nothing. That's because Flatten looks at the head of the expression (f and k respectively above), and only flattens subexpressions within with the same head.

You can see this described in the details section, etc. for the Flatten function.

share|improve this answer
1  
+1 as you actually answer the question and provide illustration...congratulations on >10K btw –  ubpdqn Jun 16 '14 at 7:23
    
Suddenly understand ,I misunderstand the meaning in the document –  user15961 Jun 16 '14 at 8:00

This does not answer your question about Flatten. However, rasher's comment does. Here are some approaches to achieve your goal:

f[f[g[a, f[b]], f[c, d]] /. f -> Sequence]

or

# /. f -> Sequence & /@ f[g[a, f[b]], f[c, d]]
share|improve this answer
    
Bases covered! +1 –  ciao Jun 16 '14 at 7:41
    
Excellent! This is what I want,thank you! –  user15961 Jun 16 '14 at 7:57

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