[Haskell-beginners] any feedback on this solution

Roelof Wobben r.wobben at home.nl
Sat Feb 7 09:37:08 UTC 2015


Hello,

I finally solved exercise 1 where I had to write a programm which checks 
if a creditcard number is valid.

I solved it this way :

toDigits :: Integer -> [Integer]
toDigits n
    | n < 0 = []
    | n < 10 = [n]
    | otherwise =  toDigits (n `div` 10) ++ [n `mod` 10]

-- | convert a number to a reversed array where a negative number will 
be a empty array
toDigitsRev :: Integer -> [Integer]
toDigitsRev 0 = [0]
toDigitsRev n
    | n < 0 = []
    | n < 10 = [n]
    | otherwise = n `mod` 10 : toDigitsRev (n `div` 10)

  -- | Doubles every second number from the right.
doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther []         = []
doubleEveryOther (x:[])     = [x]
doubleEveryOther (x:(y:zs))
    | length (x:(y:zs)) `mod` 2 /= 0 = [x] ++ (y * 2) : doubleEveryOther zs
    | otherwise = [x *2]  ++ y : doubleEveryOther zs


-- | sum all the digits of a array
sumDigits :: [Integer] -> Integer
sumDigits []  = 0
sumDigits (x:zs)
    | x < 10     = x + sumDigits zs
    | otherwise  = x `mod` 10 + x `div` 10 + sumDigits zs


-- | validate a number by looking if a number can be divided by 10
validate :: Integer -> Bool
validate n = sumDigits(doubleEveryOther(toDigits(n))) `mod` 10 == 0


-- | The main entry point.
main :: IO ()
main = do
     print $ validate  4012888888881881

Any remarks about this solution.

I know there are higher function solutions but that part is not 
descrived in chapter 1 .

Roelof



More information about the Beginners mailing list