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.

Consider the following three evaluations involving Flatten:

Flatten[f[f[f[x, y], 1, 2], f[x, y]], Infinity, f]

f[x, y, 1, 2, x, y] (* as expected *)

Flatten[List[f[f[x, y], 1, 2], f[x, y]], Infinity, f]

{x, y, 1, 2, x, y} (* as expected *)

Flatten[List[List[f[x, y], 1, 2], f[x, y]], Infinity, f]

{{f[x, y], 1, 2}, x, y} (* expected {{x, y, 1, 2}, x, y} *)

I would like to know why my expectation was wrong.

share|improve this question
add comment

1 Answer 1

up vote 13 down vote accepted

Flatten does not flatten the heads you indicate using the third optional argument, inside other heads. This is true for both the head List and other heads. In particular, the following does not come as a surprise:

Flatten[{f[{{1,2}}],f[{{3,4}}]}]

(*   {f[{{1,2}}],f[{{3,4}}]}  *)

Flattening starts at level 1, not level 0, which is why you got your first and second example working. In the last example, the List head "stops" Flatten from flattening f inside lists, but the second part, being on level 1, is flattened all right.

This design is surely intentional. If you need to flatten inside other heads, this can be easily achieved by using replacement rules. I recommend reading this thread, which contains answers describing this issue and possible solutions in more detail.

share|improve this answer
4  
Your answer makes sense. The Mathematica documentation on Flatten is very sparse. I could not anticipate this behavior from the documentation. –  m_goldberg Dec 19 '12 at 1:04
    
@m_goldberg Was glad to help, and thanks for the accept. –  Leonid Shifrin Dec 19 '12 at 2:06
add comment

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.