flatMap implemented using foldRight