"Flattening" is problematic in every programming language I know that has something like it in its library. It was born problematic in Lisp and it has continued problematic ever since. (I am aware of several Smalltalk systems offering it. With the exception of Squeak and Pharo, no two of them agree.) The fundamental problem is that which containers (if any) should be treated as leaves and which should not is not something that the language can define. It is problem-specific. Your best bet is to figure out what YOU need for YOUR problem and implement exactly that.
I was about to include some code I wrote while trying to make sense of "flattening", but no. There is no substitute for writing something that works for precisely the objects you want it to work and for no others.