flatten implemented in terms of foldLeft