Created
March 6, 2019 17:24
-
-
Save UlisseMini/d1f9551600f5427aa054b8c9a5a6d9c6 to your computer and use it in GitHub Desktop.
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
-- Sulution for https://www.seas.upenn.edu/~cis194/spring13/hw/01-intro.pdf | |
toDigits :: Integer -> [Integer] | |
toDigits n | |
| n < 1 = [] | |
| otherwise = map (\x -> read [x] :: Integer) $ show n | |
toDigitsRev :: Integer -> [Integer] | |
toDigitsRev n = reverse (toDigits n) | |
-- taken and modified from stackoverflow to be more readable, | |
-- at first i did not understand it but after messing with it in the repl now i do :) | |
doubleEveryOther :: [Integer] -> [Integer] | |
doubleEveryOther xs = fst $ foldr (\x (result, shouldDub) -> | |
( | |
-- add the result to the list | |
(if shouldDub then 2 * x else x) : result, | |
-- next pass we should do the opposite thing | |
not shouldDub | |
)) | |
-- False is used to remember if we should double the next one or not. | |
([], False) xs | |
sumDigits :: [Integer] -> Integer | |
sumDigits = sum . map sum . map (toDigits) | |
validate :: Integer -> Bool | |
validate n = | |
if (rem (sumDigits $ doubleEveryOther $ toDigits n) 10) == 0 | |
then True | |
else False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment