Flatten optimization

Functional style is a bit faster here