Given this code -- function to convert from number to list of digits toDigits :: Integer -> [Integer] toDigits n | n < 1

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899603
Joined: Mon Aug 02, 2021 8:13 am

Given this code -- function to convert from number to list of digits toDigits :: Integer -> [Integer] toDigits n | n < 1

Post by answerhappygod »

Given this code
-- function to convert from number to list of digits
toDigits :: Integer -> [Integer]
toDigits n
| n < 10 = [n]
| otherwise = (toDigits (n `div` 10)) ++ [n `mod`10]
-- function to do the same bu tin reverse
toDigitsReverse :: Integer -> [Integer]
toDigitsReverse n = reverse (toDigits n)
-- function to help double every other element of list
doubleDigitsHelper :: [Integer] -> Integer ->[Integer]
doubleDigitsHelper l t
| l == [] = []
| t == 0 = [head l] ++ (doubleDigitsHelper (drop 1l) 1)
| t == 1 = [2*(head l)] ++ (doubleDigitsHelper(drop 1 l) 0)
-- function to double every other element
doubleDigits :: [Integer] -> [Integer]
doubleDigits l = reverse (doubleDigitsHelper (reverse l) 0)
-- function to return sum of digits of a number
sumOfDigits :: Integer -> Integer
sumOfDigits n
| n < 10 = n
| otherwise = (sumOfDigits (n `div` 10)) + (n`mod` 10)
-- function to get sum of digits and then sum of list
totalDigits :: [Integer] -> Integer
totalDigits [] = 0
totalDigits (l:ls) = (sumOfDigits l) + (totalDigits ls)
-- combine all the above functions to get the requiredalgorithm
verify :: Integer -> Bool
verify n =
if ((totalDigits (doubleDigits (toDigits n)))`mod` 10) == 0
then True
else False
How does each function precisely work?(In as much detailsas possible)
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply