copied code from 6.4.2
implemented flatMap