haskell-homework/lib/Homework/Ch01/CreditCards.hs

45 lines
1.2 KiB
Haskell
Raw Permalink Normal View History

module Homework.Ch01.CreditCards where
2021-08-12 22:56:01 +00:00
toDigits :: Integer -> [Integer]
toDigits = go []
2021-08-12 22:56:01 +00:00
where
go acc 0 = acc
go acc n = go (n `mod` 10 : acc) (n `div` 10)
revDigits :: [Integer] -> [Integer]
revDigits = go []
where
go acc (x : xs) = go (x : acc) xs
go acc [] = acc
2021-08-12 22:56:01 +00:00
toDigitsRev :: Integer -> [Integer]
toDigitsRev = revDigits . toDigits
2021-08-12 22:56:01 +00:00
doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther = revDigits . go []
where
go acc (first : second : rest) = go ((second * 2) : first : acc) rest
go acc [last'] = last' : acc
go acc [] = acc
2021-08-12 22:56:01 +00:00
sumDigits :: [Integer] -> Integer
2021-08-13 23:41:59 +00:00
sumDigits digits = foldDigits 0 (+) [y | x <- digits, y <- toDigits x]
2021-08-12 22:56:01 +00:00
where
foldDigits acc f (x : xs) = foldDigits (f x acc) f xs
foldDigits acc _ [] = acc
2021-08-12 22:56:01 +00:00
validateWithParens :: Integer -> Bool
validateWithParens n = f n `mod` 10 == 0
where
f n' = sumDigits (doubleEveryOther (toDigitsRev n'))
validateWithDollars :: Integer -> Bool
validateWithDollars n = f n `mod` 10 == 0
where
f n' = sumDigits $ doubleEveryOther $ toDigitsRev n'
2021-08-12 22:56:01 +00:00
validateWithCompose :: Integer -> Bool
validateWithCompose n = f n `mod` 10 == 0
2021-08-12 22:56:01 +00:00
where
f = sumDigits . doubleEveryOther . toDigitsRev