add functional version of flatten