implemented flatMap using foldRight