Could this function be simpler with lists:foldl/r?