Skip to content

Instantly share code, notes, and snippets.

@UlisseMini
Created March 6, 2019 17:24
Show Gist options
  • Save UlisseMini/d1f9551600f5427aa054b8c9a5a6d9c6 to your computer and use it in GitHub Desktop.
Save UlisseMini/d1f9551600f5427aa054b8c9a5a6d9c6 to your computer and use it in GitHub Desktop.
-- 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