replace explicit loops with foldr