flatten implementation using flatMap