changed flatmap to use fold-right