# What is wrong with my use of Flatten? [duplicate]

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?

-

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

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

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.

-
+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]]

-
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