implementation of flatten. todo: replace union