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.

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

closed as off-topic by rasher, Ajasja, ubpdqn, m_goldberg, Öskå Jun 16 at 8:40

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question arises due to a simple mistake such as a trivial syntax error, incorrect capitalization, spelling mistake, or other typographical error and is unlikely to help any future visitors, or else it is easily found in the documentation." – rasher, Ajasja, ubpdqn, Öskå
If this question can be reworded to fit the rules in the help center, please edit the question.

4  
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. –  rasher Jun 16 at 7:13
    
Related question here –  m_goldberg Jun 16 at 7:29
    
Thank you! I think i know what the reason is.the hyperlink let me enlightened. –  user15961 Jun 16 at 7:56

2 Answers 2

up vote 6 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 at 7:23
    
Suddenly understand ,I misunderstand the meaning in the document –  user15961 Jun 16 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 –  rasher Jun 16 at 7:41
    
Excellent! This is what I want,thank you! –  user15961 Jun 16 at 7:57

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