Solution using functional programming