Created
September 17, 2014 04:51
-
-
Save johnhatfield/ed9d60b28392c82ce0d7 to your computer and use it in GitHub Desktop.
upenn HW1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In
validate
you used an operator section(==0)
; you can also use operator sections withdiv
andmod
like so:You can also use
concatMap toDigits
in place ofconcat . map toDigits
; it's part of the Prelude and will be more efficient (unless the compiler ends up doing the same optimization itself, anyway).