Validating credit card numbers - Haskell
TL;DR:


toDigits can be expressed with toDigitsRev and vice-versa.
If you use both div and mod, use divMod to get both at the same time.
You can pattern match on two elements in a list with (x:y:xs). That way you only need a single doEveryTwo.
sumDigits is sum . map (sum . toDigits).
doubleEveryOther can be written with mapAccumR, but that might be a little bit too advanced.




All in all, your code will work, but we can improve it.

Write functions in terms of other functions

You have written both toDigits as well as toDigitsRev. However, you only need one of them. The other one is the reversed variant:

toDigits :: Integer -&gt; [Integer]
toDigits = reverse . toDigitsRev


Use divMod if you need both results

You can think of divMod as

divMod x y = (div x y, mod x y)


but it's usually faster. Even better, if all your numbers are guaranteed to be positive, use quotRem, since div and mod have some constraints on their result:

toDigitsRev :: Integer -&gt; [Integer]
toDigitsRev x
  | x &lt;= 0 = []
  | otherwise = r : toDigitsRev q
 where
  (q,r) = x `quotRem` 10 -- x guaranteed to be positive


Use pattern matching to your advantage

You can match on multiple elements in a list at once. That way, you can write doEveryTwo without a helper that skips:

doEveryTwo :: (t -&gt; t) -&gt; [t] -&gt; [t]
doEveryTwo f (x:y:xs) = f x : y : doEveryTwo f xs
doEveryTwo _ [x]      = f x
doEveryTwo _ []       = []


Note that a worker-wrapper approach is usually used here for performance:

doEveryTwo :: (t -&gt; t) -&gt; [t] -&gt; [t]
doEveryTwo f = go
  where
    go (x:y:xs) = f x : y : go xs
    go [x]      = f x
    go []       = []


That way we don't have to carry f along. (Exercise: write doEveryTwo with zipWith. Have a look at cycle if you get stuck).

Use higher order function to your advantage

When you do the same for all elements in a list, it's usually time to use map. If we take a look at sumDigits, we can see that it uses toDigits for all numbers and then sums it:

sumDigits :: [Integer] -&gt; Integer
sumDigits [] = 0
sumDigits (x:xs) = sum (toDigits x) + sumDigits xs


If we write that as list comprehension, it gets more obvious:

sumDigits xs = sum [sum (toDigits x) | x &lt;- xs]


That's the same as

sumDigits xs = sum (map (sum . toDigits) xs)


or

sumDigits = sum . map (sum . toDigits)