Change reduce to foldl to handle empty list cases.