Refactor code by using match and foldLeft