Idiomatic `foldr` implementation