Improved solution via functors and applicative functors.