Skip to content

Instantly share code, notes, and snippets.

@johnhatfield
Created September 17, 2014 04:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnhatfield/ed9d60b28392c82ce0d7 to your computer and use it in GitHub Desktop.
Save johnhatfield/ed9d60b28392c82ce0d7 to your computer and use it in GitHub Desktop.
upenn HW1
-- Exercise 1
lastDigit :: Integer -> Integer
lastDigit n = n `mod` 10
dropLastDigit :: Integer -> Integer
dropLastDigit n = n `div` 10
--Exercise 2
toDigits :: Integer -> [Integer]
toDigits = reverse . toDigits'
toDigits' n
| n <= 0 = []
| otherwise = lastDigit n : toDigits' (dropLastDigit n)
--Exercise 3
doubleEveryOther' :: [Integer] -> [Integer]
doubleEveryOther' (x:y:ys) = x : (y * 2) : doubleEveryOther' ys
doubleEveryOther' x = x
doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther = reverse . doubleEveryOther' . reverse
--Exercise 4
sumDigits :: [Integer] -> Integer
sumDigits = sum . concat . map toDigits
--Exercise 5
validate :: Integer -> Bool
validate = (==0) . lastDigit . sumDigits . doubleEveryOther . toDigits
@pinealservo
Copy link

In validate you used an operator section (==0); you can also use operator sections with div and mod like so:

lastDigit = (`mod` 10)
dropLastDigit = (`div` 10)

You can also use concatMap toDigits in place of concat . map toDigits; it's part of the Prelude and will be more efficient (unless the compiler ends up doing the same optimization itself, anyway).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment