reimplementing collect/collectNested/flatten