Surely, div
and mod
are faster, but why not? I assume the problem is converting a number to a list of digits:
toDigits = map (read . (:[])) . show
56518
is converted to a String "56518"
, and each symbol in the string (every digit) is converted to a string itself with map (:[])
, at this point we have ["5","6","5","1","8"]
, and we read every single-digit string as an integer value: [5,6,5,1,8]
. Done.
Now we can calculate the sum of digits this way:
sumDigits x = sum (zipWith (*) (cycle [1,-1]) (reverse (toDigits x)))
cycle [1,-1]
makes an infinite list [1, -1, 1, -1, ...]
, which we pair with the reversed list of digits (toDigit x
), and multiply elements of every pair. So we have [8, -1, 5, -6, 5]
and its sum.
Now we can do it recursively:
isDivisible x
| x == 11 || x == 0 = True
| x < 11 = False
| x > 11 = isDivisible (sumDigits x)