Refactor (e.g., replace custom loops with foldr).